Rails uniting three models

I have the following models in my rails application

class User < ApplicationRecord 
end
class Group < ApplicationRecord 
end
class Role < ApplicationRecord 
end

Each Grouphas_many Userwith different Role. For example, Group-1they have User - Ac Role - Adminand Group-1have User - Bc Role - Memberand Group-2have User - Ac Role - Member. As a wise one Grouphas several Users, and each Userhas several Role.

Please indicate which association should I use?

+4
source share
3 answers

You can also create a table associated with Tri that has an entry for each user membership and save that user role.

class Trirelation
  belongs_to :group
  belongs_to :user
  belongs_to :role
end

class User
  has_many :trirelations
  has_many :groups, through: :trirelations
end

class Group
  has_many :trirelations
  has_many :users, through: :trirelations
end

class Role
  has_many :trirelations
end

, ,

@role = Trirelation.find_by(user_id: 1, group_id: 21).role.name
+1

, .

:

class Group < ApplicationRecord 
  has_many :users
end

class User < ApplicationRecord 
  belongs_to :group
  belongs_to :role
end

class Role < ApplicationRecord 
  has_many :users
end

, :

:

group_id:integer:index
role_id:integer:index

1:

.

class Group < ApplicationRecord 
  has_many :users
  has_many :roles
end

class User < ApplicationRecord 
  belongs_to :group
end

class Role < ApplicationRecord 
  belongs_to :group
end

, :

:

group_id:integer:index

group_id:integer:index

, :

user = User.last
user.group # Returns group of the user
user.group.roles # Returns roles of the user
+1

Incase, , , , ...

class Group < ApplicationRecord 
  has_many :group_users
  has_many :users, through: :group_users

  has_many :group_user_roles
  has_many :roles, through: :group_user_roles
end

class User < ApplicationRecord 
  has_many :group_users
  has_many :groups, through: :group_users

  has_many :group_user_roles
  has_many :roles, through: :group_user_roles
end

class GroupUser < ApplicationRecord
    belongs_to :group
    belongs_to :user
end

class Role < ApplicationRecord
end

class GroupUserRole < ApplicationRecord
  belongs_to :user
  belongs_to :group
  belongs_to :role
end

(GroupUserRole), .

+1

Source: https://habr.com/ru/post/1692858/


All Articles