Skip to content
Tags

Multiple relationships between same models

December 1, 2010

Ok,

So I have two models, Groups and Users

1. Groups has many Users as members

2. Users can be members of many groups.

I am implementing this using has_many :through

Now,

3. User can own multiple groups

4. Groups have one owner.

How do I implement this ? I need the models to distinguish between the two relationships, and am quite reluctant on adding another model called ownership.

I came across this:

http://efreedom.com/Question/1-3251736/Two-Resources-Two-Different-Relationships-Rails


class User < ActiveRecord::Base
has_many :memberships
has_many :groups, :through => :memberships
has_many :owned_groups, :class => "Group"

end

class Group < ActiveRecord::Base

has_many :memberships

has_many :members, :through => :memberships, :source => :user

belongs_to :owner, :class_name => "User", :foreign_key => :owner_id

end

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

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: