Rails 4:从控制台进行简单的通配符搜索

时间:2013-10-25 15:29:46

标签: ruby-on-rails postgresql

从控制台对字段进行快速通配符搜索的最简单方法是什么?我不在乎防止SQL注入。

我正在使用 PostgreSQL

使用包含“emerge”

的字符串搜索title

这有效,但有点麻烦。好奇如果有速记?

Product.where("title @@ :q", q: "emerging")

同样繁琐但在Rails 4中似乎不再适用于我:

Product.where("title ILIKE ?", "emerging")
Product.where("title ilike :q", q: "emerging")

我想我正在寻找像Product.where(title: "*emerging*")

这样的东西

2 个答案:

答案 0 :(得分:12)

这应该这样做:

word = 'emerging'
Product.where('title ILIKE ?', "%#{word}%")
  • ILIKE使搜索对案例不敏感
  • “%”通配符使搜索匹配每个产品,其中包含标题内含“或”内容(或不包含)之前和/或之后的内容。

答案 1 :(得分:3)

使用LIKE,如下所示:

Product.where('title LIKE ?', '%emerging%')