Rails (ActiveRecord) many to many table Rails (ActiveRecord) many to many table ruby-on-rails ruby-on-rails

Rails (ActiveRecord) many to many table


Here are a couple of tutorials that should help. Basically there two approaches to make many-to-many work, either has_and_belongs_to_many or has_many :through (recommended).

links:

  1. http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off
  2. http://railscasts.com/episodes/47-two-many-to-many
  3. http://railscasts.com/episodes/154-polymorphic-association


In Rails 3 you want to make a join table for many to many relationships, using the plural names of the tables you want to join in alphabetical order. So in this case it would be groups_users.

models

class GroupsUser < ActiveRecord::Base  belongs_to :user  belongs_to :groupendclass User < ActiveRecord::Base  has_many :groups_users  has_many :groups, :through => :groups_usersendclass Group < ActiveRecord::Base  has_many :groups_users  has_many :users, :through => :groups_usersend


I [added] another column to [users_groups]...The question is how do I access it from a model without using a custom SQL call?

It sounds like you want to access a column of your user_groups table by calling a method on your User model or your Group model.

Some suggestions:

I'd name the table "user_groups" to work with ActiveRecord's pluralization expectations, but I'm not sure if that's essential.

Following Dave's advice, you'd want to set things up using the "has_many :through" technique...

# Declare a Model based on the many-to-many linking table.class UserGroup < ActiveRecord::Base  belongs_to :user  belongs_to :groupendclass User < ActiveRecord::Base  has_many :user_groups  has_many :groups, :through => :user_groupsendclass Group < ActiveRecord::Base  has_many :user_groups  has_many :users, :through => :user_groupsend

Is there a way to change the third column in this table from a user model?

This is a little unclear, but keep in mind that each User can have a lot of UserGroups. So if you wanted to change that third column you'd have to find the particular one you're looking for.