Ayman Salah
Ayman Salah

Reputation: 1089

Ruby on Rails Multiple relationship roles using one model

Group:

Each of the creator/admin/member are Users. I need to be able to call these from each user:

How can I achieve this? I know that I can do something like this. How will it be from the User's side?

class Group < ActiveRecord::Base
    has_one :creator, :class :user
    has_many :admins, :class :user
    has_many :memebers, :class :user
end

Upvotes: 0

Views: 175

Answers (2)

Nermin
Nermin

Reputation: 6100

in User model

class User < ActiveRecord::Base
  has_many :my_groups,
        :class_name => "Group",
        :foreign_key => :creator_id
  has_and_belongs_to_many :controlled_groups,
        :class_name => "Group",
        :join_table => :admins_groups
  has_and_belongs_to_many :joined_groups,
        :class_name => "Group",
        :join_table => :groups_members
end

in Group model

class Group < ActiveRecord::Base
    belongs_to :creator, :class_name => "User"
    has_and_belongs_to_many :admins,
           :class_name => "User",
           :join_table => :admins_groups
    has_and_belongs_to_many :members,
           :class_name => "User",
           :join_table => :groups_members
end

Migration

# migration to create join table for admins and groups
def change
   create_table :admins_groups, :id => false do |t|
      t.integer :user_id
      t.integer :group_id
   end
end

# migration to create join table for members and groups
def change
   create_table :groups_members, :id => false do |t|
      t.integer :user_id
      t.integer :group_id
   end
end
# in migration where you create groups table
def change
   create_table :groups do |t|
      # ....  all other fields
      t.integer :creator_id # id for group creator
      t.timestamps
   end
end

Upvotes: 2

argentum47
argentum47

Reputation: 2382

For each has_many you would need a belongs_to in the User class. Then you can have scopes or class methods for your User._ requirements.

like :

class User < ..
  scope :mygroups, ->{ where(:id => "Group.creator_id") }
  scope :controlledgroups, ->{ where(:id => "Group.admin_id") }
end

There are other ways to write the query depending the way you prefer, if you would have a boolean field in User saying admin: true then it would be different. But you do need to specify foreign keys like

has_many :admins, class_name: "User", foreign_key: "admin_id"

Upvotes: 1

Related Questions