Rails 自引用 has_one 在嵌套模型上具有动态条件 - 基于管理员员工客户角色

Rails self referencing has_one with dynamic condition on nested model - Admin Employee Client role based

我有一个具有 3 个角色的独特用户模型:admin、:employee、:client (devise + pundit)

管理员创建员工, Employee belongs_to PrimaryBusiness(就职的公司) 员工与客户一起创建业务(它是公司和客户的组合)

所以, 业务包含一个 user_id,即员工 ID

由于客户属于企业,而企业包含员工,我怎样才能获得具有 has_one 关联的员工(用户)?

基本上,我想在 User has_one:creator 中使用这个方法,我想这是有道理的:

# User.rb
get_creator
  User.find(current_user.primary_business.user_id)
end

更一般地说,这是处理层次结构的正确方法吗 管理员(用户)> 员工(用户)> 业务 > 客户(用户)? 我在层次结构中将业务放在客户之前,因为客户可以离开业务,但业务仍然存在。

#User.rb
class User < ActiveRecord::Base
has_many :businesses
belongs_to :primary_business, class_name: "Business", foreign_key: "business_id"
end

#Business.rb
class Business < ActiveRecord::Base
belongs_to :user #here is the Employee
has_many :clients, class_name: "User", foreign_key: 'business_id' #here are 
the clients 
end

到目前为止我得到的最接近的是:

# User.rb
has_one :creator, ->(user) {where id:  user.primary_business.user_id }, class_name: self, foreign_key: "id"

但是因为我自己引用了用户,这个结果是 user.id = 1 AND user.id = 2,然后 return nil 谢谢

是的,这似乎是处理该关联链的正确方法。

顺序可能有点棘手:

Admins -> Businesses -> Employees -> Businesses -> Clients

编辑:要在创建者的用户模型上添加 has_one 关联,我们可以这样做:

has_one :creator, through: :primary_business, source: :user

我还将 'clients' 关联更改为 'users',因为它将包含员工和客户。为了简单起见,我个人的偏好也是将 'primary_business' 关联更改为 'business',但这取决于您。