Rails 预先加载(包括)和 where 子句不起作用?

Rails Eager loading (includes) and where clause is not working?

我正在使用 Rails 4.1,我的模型类似于:

Client has_many TicketLists
TicketList has many projects

现在我正在尝试在客户端模型中使用预加载,例如:

class Client < ActiveRecord::Base
  def ticket_lists_with_project_id(project_id)
    ticket_lists.includes(:projects).where("projects.id = ?", project_id)
  end  
end  

当我这样做时:

Client.find(2).ticket_lists_with_project_id(1)
  Client Load (1.7ms)  SELECT  "clients".* FROM "clients"  WHERE "clients"."is_destroyed" = 'f' AND "clients"."is_closed" = 'f' AND "clients"."id" =  LIMIT 1  [["id", 2]]
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "projects"
LINE 1: ...d" = 'f' AND "ticket_lists"."client_id" =  AND (projects.i...
                                                             ^
: SELECT "ticket_lists".* FROM "ticket_lists"  WHERE "ticket_lists"."is_destroyed" = 'f' AND "ticket_lists"."client_id" =  AND (projects.id = 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "projects"
LINE 1: ...d" = 'f' AND "ticket_lists"."client_id" =  AND (projects.i...

这可能对您有帮助:

Client.includes(:ticket_lists => :projects).where("clients.id = ? ", 2)

class Client < ActiveRecord::Base
  def ticket_lists_with_project_id(project_id)
    Client.includes(:ticket_lists => :projects).where("projects.id = ?", project_id)
  end  
end 

而不是这个:

ticket_lists.includes(:projects).where("projects.id = ?", project_id)

这样做:

ticket_lists.joins(:projects).where("projects.id = ?", project_id)

因为你用的是Rails4,你可以让它看起来更可爱:

ticket_lists.joins(:projects).where(projects: {id: project_id})

试试下面的方法:

class Client < ActiveRecord::Base
  def ticket_lists_with_project_id(project_id)
    ticket_lists.includes(:projects)
                .where("projects.id = ?", project_id)
                .references(:projects)
  end  
end

它会起作用的。如果你想 add conditions 到你包含的模型,你必须明确引用它们。另外 请注意 includes 使用关联名称而 references 需要实际的 table 名称。