我試圖用Ruby,ActiveRecord和MySQL在報價數據庫中搜索多個詞。我做的方式如下所示,它正在工作,但我想知道是否有更好的方法。用Ruby和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的全文搜索 – 2011-03-11 19:56:47
,我會推薦'to_s.downcase.strip.split.uniq'將其摺疊爲小寫並刪除重複的單詞。 – 2011-03-12 05:17:29
我正在使用Rails 2.3.5,但無論如何,答案有很大幫助。謝謝。 – Eduardo 2011-03-12 14:37:48