straightflush-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
2007-Nov-12 15:29 UTC
has_many + habtm on same model
Hello, In a situation where a user has_many :groups (it owns the group) but also has_and_belongs_to_many :groups, how is this most easily represented? The only way i have found is user.rb: has_many :groups has_and_belongs_to_many :memberships, ,:join_table => ''memberships'', :class => ''group'' group.rb belongs_to :user has_and_belongs_to_many :memberships, , :join_table => ''memerships'', :class => ''user'' I think there is an opportunity to have a new model membership.rb that belongs_to :user, belongs_to :group where a user has_many :groups, :through => :membership but not 100% sure. What is the cleanest approach here? Adam --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---
unknown wrote:> Hello, > > In a situation where a user has_many :groups (it owns the group) but > also > has_and_belongs_to_many :groups, how is this most easily represented? > > The only way i have found is > > user.rb: > has_many :groups > has_and_belongs_to_many :memberships, ,:join_table => ''memberships'', > :class => ''group'' > > group.rb > belongs_to :user > has_and_belongs_to_many :memberships, , :join_table => ''memerships'', > :class => ''user'' > > > I think there is an opportunity to have a new model membership.rb that > belongs_to :user, belongs_to :group where a user has_many :groups, > :through > => :membership but not 100% sure. > > What is the cleanest approach here?User: has_many :owned_groups, :class_name => "Group" has_many :memberships, :dependent_destroy has_many :groups, :through => :memberships Group: belongs_to :owner, :class_name => "User" has_many :memberships, :dependent_destroy has_many :users, :through => :memberships That''s how I''d do it. You want to keep the association names distinct (and meaningful too). -- Josh Susser http://blog.hasmanythrough.com -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---