Ruby-on-rails 可以使用activerecord 查找字段的子字符串吗?(快速而肮脏的关键字查找器)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5044372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can you use activerecord to find substring of a field? (quick & dirty keyword finder)
提问by jpw
Suppose a database contains a field 'keywords' and sample records include: "pipe wrench" "monkey wrench" "crescent wrench" "crescent roll" "monkey bars"
假设一个数据库包含一个字段“关键字”,样本记录包括:“管扳手”“猴子扳手”“月牙扳手”“月牙辊”“猴子棒”
is there a way in activerecord to find the records where the keyword field contains the substring "crescent"?
有没有办法在 activerecord 中找到关键字字段包含子字符串“新月”的记录?
(It's just a quick and dirty lookup for a quick concept prototype)
(这只是快速概念原型的快速查找)
回答by Pan Thomakos
Yeah, just use a LIKE statement in MySQL.
是的,只需在 MySQL 中使用 LIKE 语句。
In Rails 2.x:
在 Rails 2.x 中:
Table.find(:all, :conditions => ['keywords LIKE ?', '%crescent%'])
In Rails 3.x:
在 Rails 3.x 中:
Table.where('keywords LIKE ?', '%crescent%').all
回答by Martin ?hlin
The Postgres database syntax would be:
Postgres 数据库语法为:
YourModelName.where("yourFieldName like ?", "%" + yourSearchTerm + "%")
回答by christianblais
It all depends on your DB. Is it Postgres? MySQL? MongoDB? Anything else?
这一切都取决于您的数据库。是 Postgres 吗?MySQL?MongoDB?还要别的吗?
With Postgres, you could use something like :
使用 Postgres,您可以使用以下内容:
Rails 2.x => Model.find(:all, :conditions=>["models.keywords ~= ?", 'crescent'])
Rails 3.x => Model.where("models.keywords ~= ?", 'crescent')
You just have to find the right syntax for your DB / Rails / ActiveRecord version.
您只需要为您的 DB / Rails / ActiveRecord 版本找到正确的语法。
回答by user3916244
I had a similar issue. I needed to see if there are keywords passed from conrolled input in the frontend component in the body of any questions in my questions table. Here is how I did it in my controller:
我有一个类似的问题。我需要查看在我的问题表中的任何问题的正文中是否有从前端组件中的控制输入传递的关键字。这是我在控制器中的做法:
def search
input = params[:q]
@questions = Question.all
search_words = input.split(' ')
@found_question = [];
search_words.each do |word|
@found_question << Question.where("questions.body LIKE ?", "%#{word}%")
end
end

