Rails 4.1 ActiveRecord - 在查询中使用关联模型属性

Rails 4.1 ActiveRecord - Using Associated Model Properties in Query

我正在我的应用程序中构建搜索,我有三个模型:公司、汽车和所有者

class Company < ActiveRecord::Base
  has_many :cars
end

class Car < ActiveRecord::Base
  belongs_to :company
  has_many :owners
end

class Owner < ActiveRecord::Base
  belongs_to :car
end

每个模型都有一个 name 字段。

我正在尝试编写一个 ActiveRecord 查询,returns 所有姓名、汽车名称或汽车公司名称包含搜索查询的车主。因此,如果车主的姓名不包含搜索查询但他的汽车名称包含,车主仍将被返回。

这是我目前所做的:

sql_query = "%honda%"

@results = Owner.includes(:car => :company).where("name LIKE ? OR cars.name LIKE ? OR companies.name LIKE ?", sql_query, sql_query, sql_query)

但是,当查询 运行:

时,我收到以下错误消息
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "cars"

我查看了关于 this SO 问题的标记答案,但是当我将它应用到我的模型时,答案似乎不起作用。

如有任何帮助,我们将不胜感激!

您需要使用 references 方法以便 Rails 添加所需的 JOIN。 Like so.

您的代码将变成

@results = Owner.includes(:car => :company).where("name LIKE ? OR cars.name LIKE ? OR companies.name LIKE ?", sql_query, sql_query, sql_query).references(:cars, :companies)

请注意 references 使用实际的 table 名称,与 includes 使用关联名称不同