Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails (ActiveRecord) many to many table

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

like image 875
Ori Avatar asked Jul 21 '09 17:07

Ori


2 Answers

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
like image 171
dave elkins Avatar answered Oct 26 '22 23:10

dave elkins


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 :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
like image 21
bigpotato Avatar answered Oct 26 '22 23:10

bigpotato