views:

1007

answers:

2

I have two models, Users and Groups. Each group can have many users and each user can be in many groups.

I currently have something simple like:

User:

has_many    :groups

Group:

has_many    :users

So I have a groups_users table which is just creating rows with group_id and user_id. I want to add another column to this, (which I have), the question is how do I access it from a model without using a custom SQL call? In the group model I can go self.users and in user I can go self.groups

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

Sorry if this is confusing, please advise on this

+6  A: 

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://www.jumbabox.com/2008/06/ruby-on-rails-many-to-many-tutorial/
  2. http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off
  3. http://railscasts.com/episodes/47-two-many-to-many
  4. http://railscasts.com/episodes/154-polymorphic-association
dave elkins
A: 

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 :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 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.

Ethan