Rolify 与具有特定角色的用户建立关联

Rolify make association to a user with a specific role

我想建立一个关联,其中一个用户有很多交易,一个交易属于一个用户以及另一个具有角色的用户 ('associate')。

我正在使用 rolify gem 来执行此操作。

像这样:

# user.rb

has_many :deals
# deal.rb

belongs_to :user
belongs_to :associate # User with role 'associate or admin'

第一个属于可以是任何用户,无论该用户是任何角色它仍然可以工作,第二个属于但绝对应该是助理或管理员

你认为我应该为此使用 rolify 吗?或者我不应该为每个角色制作不同的模型?

更新

我当前的解决方案不起作用,因为作为关联的用户需要两个关联,有很多交易和 has_many :client_deals。我仍然不确定命名。

更新 2

Max 的解决方案非常有效!

对于合作伙伴,您可以使用以下内容

belongs_to :associate, -> { includes(:roles).where(roles: {name: ['associate', 'admin'] }) }, class_name: 'User', foreign_key: 'user_id'

这不是您要使用 Rolify 的 table 的地方。 Rolify 通过 roles table 在角色和资源之间创建一对一的关联。然后角色通过 users_roles table 与用户建立多对多关联。

这意味着它适用于一对多或多对多关联的情况,但 Rolify 确实不能保证只有一个用户具有特定角色,因为缺少数据库约束。

即使您添加了验证或其他应用程序级别的约束,但仍然存在竞争条件的可能性,只需双击即可。

相反,您只想创建单独的一对一关联:

class Deal < ApplicationRecord
  belongs_to :creator, 
    class_name: 'User',
    inverse_of: :created_deals
  belongs_to :associate, 
    class_name: 'User',
    inverse_of: :deals_as_associate

  validates :must_have_associate_role!

  private
  def must_have_associate_role!
    # this could just as well be two separate roles...
    errors.add(:associate, '^ user must be an associate!') unless associate.has_role?(:associate)
  end
end

class User < ApplicationRecord
  has_many :created_deals, 
    class_name: 'Deal'
    foreign_key: :creator_id,
    inverse_of: :creator
  has_many :deals_as_associate, 
    class_name: 'Deal'
    foreign_key: :associate_id,
    inverse_of: :associate
end

只要每个关联的名称是唯一的并且您使用 class_nameforeign_key 选项正确配置,两个模型之间实际上可以有无限数量的关联。

由于这使用单个外键,这意味着 ere 永远只能是一个,并且您可以防止竞争条件。