[ACCEPTED]-Rails (ActiveRecord) many to many table-many-to-many

Accepted answer
Score: 15

Here are a couple of tutorials that should 3 help. Basically there two approaches to 2 make many-to-many work, either has_and_belongs_to_many 1 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
Score: 12

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

models

class GroupsUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

class User < ActiveRecord::Base
  has_many :groups_users
  has_many :groups, :through => :groups_users
end

class Group < ActiveRecord::Base
  has_many :groups_users
  has_many :users, :through => :groups_users
end
Score: 4

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

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

Some suggestions:

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

Following Dave's advice, you'd 7 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 :group
end

class User < ActiveRecord::Base
  has_many :user_groups
  has_many :groups, :through => :user_groups
end

class Group < ActiveRecord::Base
  has_many :user_groups
  has_many :users, :through => :user_groups
end

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

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

More Related questions