我有一个具有某些关系的User模型:
class User < ApplicationRecord
has_many :hierarchies
has_one :hierarchy, -> { where(end_at: nil) }
has_one :boss, through: :hierarchy
has_one :department, through: :hierarchy
end
我正在尝试在视图中使用此数据:
@users = current_team.active_users.
order(director: :desc, leader: :desc, active: :desc, nickname: :asc).
includes(:department, :boss, :hierarchy)
当我遍历每个用户时,user.department
和user.boss
可以正常工作,没有新的查询,但是层次结构却没有。每次我尝试访问user.hierarchy
时,都会触发一个新查询:
CACHE Hierarchy Load (0.0ms) SELECT "hierarchies".* FROM "hierarchies" WHERE "hierarchies"."user_id" = $1 AND "hierarchies"."end_at" IS NULL ORDER BY "hierarchies"."id" DESC LIMIT $2 [["user_id", 115], ["LIMIT", 1]]
这个答案(https://stackoverflow.com/a/34865972/5077874)让我对关系的问题where filter
有什么看法,但我无法解决。