我想建立一个用户有很多交易并且一个交易属于一个用户以及另一个具有角色的交易的关联(“关联”)。
我正在使用rolify宝石来做到这一点。
像这样:
# 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的解决方案效果很好!
这不是您要使用Rolify表格的地方。Rolify通过roles
表在角色和资源之间创建一对一的关联。然后,角色通过users_roles
表与用户进行多对多关联。
这意味着它在一对多或多对多关联的情况下非常有用,但是由于缺乏数据库约束,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_name
和foreign_key
选项正确配置,两个模型之间的关联数就可以无限增加。
由于它使用单个外键,因此这意味着ere永远只能是一个,并且可以防止竞争。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句