Double belongs to in AR?

Can you do a double belongs to in ActiveRecord? I wanted a column made up of user ids matched with group ids (since I can't think of a better way with my current knowledge of AR).

Something like the following:

class User<ActiveRecord::Base    has_many user_groups end

class Group<ActiveRecord::Base end

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

#how would you make that work?

Thanks,              Kyle

You are very very close:

class User<ActiveRecord::Base has_many :user_groups

has_many :groups, :through=>:users end

class Group<ActiveRecord::Base

has_many :user_groups

has_many :users, :through=> :user_groups end

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

Might I suggest a name change? UserGroup might work better as Membership. It reads better, and it represents the actual entity you’re trying to handle. You can then use that model to manage the relationships directly. Find that record, delete it, and a user is no longer a member of a group.

group = Group.find(15)

group.memberships.create :user=>User.find(1) #add to a group

Membership.create(:user_id=>2, :group_id=>15) #another way to add to a group

Membership.find_by_user_id_and_group_id(1,15).destroy #delete a user from a group

Hope that helps!