假设数据库包含字段'keywords',样本记录包括: “管扳手” “猴子扳手” “新月扳手” “新月卷” “猴子酒吧”
在activerecord中有一种方法可以找到关键字字段包含子串“crescent”的记录吗?
(这只是对快速概念原型的快速而肮脏的查找)
答案 0 :(得分:77)
是的,只需在MySQL中使用LIKE语句。
在Rails 2.x中:
Table.find(:all, :conditions => ['keywords LIKE ?', '%crescent%'])
在Rails 3.x中:
Table.where('keywords LIKE ?', '%crescent%').all
答案 1 :(得分:15)
Postgres数据库语法为:
YourModelName.where("yourFieldName like ?", "%" + yourSearchTerm + "%")
答案 2 :(得分:9)
这一切都取决于你的数据库。是Postgres吗? MySQL的? MongoDB的?还有什么吗?
使用Postgres,你可以使用类似的东西:
Rails 2.x => Model.find(:all, :conditions=>["models.keywords ~= ?", 'crescent'])
Rails 3.x => Model.where("models.keywords ~= ?", 'crescent')
您只需要为DB / Rails / ActiveRecord版本找到正确的语法。
答案 3 :(得分:1)
我有一个类似的问题。我需要查看问题表中任何问题正文的前端组件中是否有从可卷曲的输入传递来的关键字。这是我在控制器中执行的操作:
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