【发布时间】:2011-03-11 16:56:42
【问题描述】:
我正在尝试使用 Ruby、ActiveRecord 和 MySQL 在报价数据库中完成多字搜索。我的方法如下所示,并且可以正常工作,但是我想知道是否有更好的方法。
# receives a string, splits it in a array of words, create the 'conditions'
# query, and send it to ActiveRecord
def search
query = params[:query].strip.split if params[:query]
like = "quote LIKE "
conditions = ""
query.each do |word|
conditions += (like + "'%#{word}%'")
conditions += " AND " unless query.last == word
end
@quotes = Quote.all(:conditions => conditions)
end
我想知道是否有更好的方法来组成这个“条件”字符串。我还尝试使用字符串插值,例如使用 * 运算符,但最终需要更多的字符串处理。提前致谢
【问题讨论】:
标签: mysql ruby search activerecord