Skip to content

Multiple relationships between same models

December 1, 2010


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


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:

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


class Group < ActiveRecord::Base

has_many :memberships

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

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


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


From → Uncategorized

Leave a Comment

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: