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)
Mar*_*lin 15
Postgres数据库语法将是:
YourModelName.where("yourFieldName like ?", "%" + yourSearchTerm + "%")
Run Code Online (Sandbox Code Playgroud)
这一切都取决于你的数据库.是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版本找到正确的语法.
| 归档时间: |
|
| 查看次数: |
35339 次 |
| 最近记录: |