你可以使用activerecord来查找字段的子字符串吗?(快速和脏的关键字查找器)

jpw*_*ynn 43 activerecord ruby-on-rails

假设一个数据库包含一个字段'关键字',样本记录包括:"管扳手""猴子扳手""新月扳手""新月形卷""猴子栏"

有没有办法在activerecord中找到关键字字段包含子串"crescent"的记录?

(这只是对快速概念原型的快速而肮脏的查找)

Pan*_*kos 82

是的,只需在MySQL中使用LIKE语句即可.

在Rails 2.x中:

Table.find(:all, :conditions => ['keywords LIKE ?', '%crescent%'])
Run Code Online (Sandbox Code Playgroud)

在Rails 3.x中:

Table.where('keywords LIKE ?', '%crescent%').all
Run Code Online (Sandbox Code Playgroud)

  • 不,Rails自动转义参数.`where("关键字LIKE'#{query}'")`易受攻击,但`where("关键字LIKE?",查询)`不是. (8认同)
  • Rails 4与Rails 3的工作方式与此问题相同. (7认同)
  • 想知道这个查询有多贵吗?我在一个大型数据库上运行它,它冻结了。 (3认同)

Mar*_*lin 15

Postgres数据库语法将是:

YourModelName.where("yourFieldName like ?", "%" + yourSearchTerm + "%")
Run Code Online (Sandbox Code Playgroud)


chr*_*ais 9

这一切都取决于你的数据库.是Postgres吗?MySQL的?MongoDB的?还要别的吗?

使用Postgres,您可以使用以下内容:

Rails 2.x => Model.find(:all, :conditions=>["models.keywords ~= ?", 'crescent'])
Rails 3.x => Model.where("models.keywords ~= ?", 'crescent')
Run Code Online (Sandbox Code Playgroud)

您只需要为DB/Rails/ActiveRecord版本找到正确的语法.