我有一个独特的用户模型,有3个角色:admin,:employee,:client(devise + pundit)
管理员创建员工, 员工belongs_to PrimaryBusiness(它所在的公司) 员工通过客户(公司和客户组合)创建业务
所以, Business包含user_id,即Employee 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,这个结果到user.id = 1 AND user.id = 2,然后返回nil 谢谢
答案 0 :(得分:0)
是的,这似乎是进行这种关联链的正确方法。
订单可能有点棘手:
管理员 - &gt;企业 - &gt;员工 - &gt;企业 - &gt;客户端
编辑:要在创建者的用户模型上添加has_one关联,我们可以这样做:
has_one :creator, through: :primary_business, source: :user
我也会改变客户&#39;与用户的关联&#39;因为它将包含员工和客户。我个人的偏好也是改变'primary_business&#39;与“商业”联系为简单起见,但这取决于你。