unknown
November 12, 2007, 4:29pm
1
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
unknown
November 12, 2007, 6:42pm
2
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 S.
http://blog.hasmanythrough.com