我有3个型号,用户,部门和员工。员工属于User&分别存储一个名为role的值。目前有2个角色是“1”和“2”。以下是我的关系。
用户:
class User < ActiveRecord::Base
has_many :staffs, :dependent => :destroy
# manager view
has_many :manage_divisions, -> { where staffs: { role: 1 } }, :through => :staffs, :source => :division
has_many :manage_division_staffs, :through => :manage_divisions, :source => :staffs
# staff view
has_many :work_for_divisions, -> { where staffs: { role: 2 } }, :through => :staffs, :source => :division
has_many :work_for_division_staffs, :through => :work_for_divisions, :source => :staffs
end
我想通过User.manage_divisions获取用户通过staff表管理的部门。然后通过User.manage_division_staffs获取这些部门的工作人员列表。但是现在当我打电话给User.manage_division_staffs时,看起来有些角色= 1的职员(但不是所有员工)。我也想为User.work_for_divisions做类似的事情。
下面是我调用User.manage_division_staffs时生成的sql查询:
SELECT "staffs".*
FROM "staffs"
INNER JOIN "divisions" ON "staffs"."division_id" = "divisions"."id"
INNER JOIN "staffs" "staffs_manage_division_staffs_join" ON "divisions"."id" = "staffs_manage_division_staffs_join"."division_id"
WHERE "staffs"."role" = 1
AND "staffs_manage_division_staffs_join"."user_id" = ? [["user_id", 3]]
我知道我做错了什么,但我不知道纠正它的方法。任何想法??