我正在尝试使用 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
我想知道是否有更好的方法来组成这个“条件”字符串。我也尝试过使用字符串插值,例如使用 * 运算符,但最终需要更多的字符串处理。提前致谢
最佳答案
首先,我强烈建议您将模型的逻辑转移到模型中。不要在 Controller 中创建搜索逻辑,而是在报价模式中创建一个#search 方法。
class Quote
def self.search(query)
...
end
end
你的 Controller 变成了
# receives a string, splits it in a array of words, create the 'conditions'
# query, and send it to ActiveRecord
def search
@quotes = Quote.search(params[:query])
end
现在,回到最初的问题。您现有的搜索逻辑犯了一个非常严重的错误:它直接插入值打开您的代码以进行 SQL 注入(inject)。假设您使用 Rails 3,您可以利用新的#where 语法。
class Quote
def self.search(query)
words = query.to_s.strip.split
words.inject(scoped) do |combined_scope, word|
combined_scope.where("quote LIKE ?", "%#{word}%")
end
end
end
有点高级的话题。如果您想了解 combined_scope
+ inject
的作用,我建议您阅读文章 The Skinny on Scopes .
关于mysql - 使用 Ruby 和 MySQL 进行多词搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5275876/