在相关的 table 上使用 "WHERE ... LIKE" 的范围

Scope with "WHERE ... LIKE" on a related table

我正在尝试从 Postgresql table (table1) 中获取数据,该数据由另一个相关 table (table2).

在纯 SQL 中,我会这样写查询:

SELECT * FROM table1 JOIN table2 USING(table2_id) WHERE table2.property LIKE 'query%'

这工作正常:

scope :my_scope, ->(query) { includes(:table2).where("table2.property": query) }

但我真正需要的是使用 LIKE 运算符进行过滤,而不是严格相等。但是这不起作用:

scope :my_scope, ->(query) { includes(:table2).where("table2.property LIKE ?", "#{query}%") }

因为我收到这个错误:

PG::UndefinedTable: ERROR: missing FROM-clause entry for table "table2" LINE 1: ...ble2" WHERE "table1"."user_id" =  AND (tabl... ^ : SELECT "table1".* FROM "table1" WHERE "table1"."user_id" =  AND (table2.property LIKE 'query%') ORDER BY last_used_at DESC

我做错了什么?

通过这种方式尝试,在查询中添加[]

scope :my_scope, ->(query) { includes(:table2).where(["table2.property LIKE (?)", "#{query}%"]) }

也可以尝试添加 (?)

.includes() 通常运行 2 个单独的查询,除非它发现您的条件强制执行单个 LEFT OUTER JOIN 查询,但在您的情况下它无法这样做,因为引用在字符串中(请参阅this example).

您可以通过指定 .references(:table2):

强制执行单个查询行为
scope :my_scope, ->(query) { includes(:table2)
                               .references(:table2)
                               .where("table2.property LIKE ?", "#{query}%") }

或者你可以只使用 .eager_load():

scope :my_scope, ->(query) { eager_load(:table2)
                               .where("table2.property LIKE ?", "#{query}%") }