user.roles << role user. . .
, , : has_and_belongs_to_many, . Rails has_many :through, " " .
, (, , ) has_many/belongs_to. " " Rails. :
class Role
has_many :users
end
class User
belongs_to :role
end
, , , UserRole, has_many :through UserRole.
class User
has_many :user_roles
has_many :roles, through: :user_roles
end
class UserRole
belongs_to :user
belongs_to :role
validates :user_id, uniqueness: { scope: :role_id }
validate :at_most_3_roles, on: :create
def at_most_3_roles
duplicates = UserRole.where(user_id: user_id, role_id: role_id).where('id != ?', id)
if duplicates.count > 3
errors.add(:base, 'A user may have at most three roles')
end
end
end
class Role
has_many :user_roles
has_many :users, through: :user_roles
end