“包含”不适用于与过滤器相关的轨道

时间:2018-10-04 14:32:31

标签: ruby-on-rails activerecord ruby-on-rails-5

我有一个具有某些关系的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.departmentuser.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有什么看法,但我无法解决。

0 个答案:

没有答案