1

我有一个Product模型和一个Order模型。假设一个订单有一个产品。

我想搜索产品名称中包含“fruity”一词的所有订单

以下查询允许我检索关联产品名称等于“fruity”的所有订单

Order.joins(:product).where(:products => {:name => "fruity"})

但我想做的是使用LIKE运营商。如何使用查询界面执行此操作?

4

2 回答 2

4

Rails 指南非常清楚地说明了这一点。

您需要一个参数化的字符串参数来where

Order.joins(:product).where('products.name like ?', '%fruity%')

and通过将哈希传递给 ActiveRecord,您无法做任何比相等和基于分组更复杂的事情;如果你想要否定, or LIKE, or or, 你需要编写一个参数化的 SQL 片段:

...where('name = ? or name = ?', 'joe', 'bob') # only way to get 'or'
...where('name != ?', 'john') # only way to get 'not equal'

从 Rails 4 开始,他们已经通过where.not.

于 2013-11-05T05:34:14.917 回答
0

squeelgem https://github.com/ernie/squeel#compound-conditions让您无需编写原始 SQL 即可执行此操作。

于 2013-11-05T05:38:16.417 回答