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!
On Nov 28, 2007 9:45 AM, Kyle Schmitt
<kyleaschmitt-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
>
> 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 received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---