mysql - 使用 Ruby 和 MySQL 进行多词搜索

标签 mysql ruby search activerecord

我正在尝试使用 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/

相关文章:

php - 查找数据库中与最多关键字匹配的记录

php - mysql 和 php FULLTEXT 搜索做得更多,但做得不多?

mysql - 使用 GROUP BY 时计算 2 列上的不同值

ruby - Directory的mkdir和新方法之间的区别

php - 如何在表(MySQL DB)中为一行存储大量数据(超过 3000 行)?

ruby-on-rails - 无法打开 CSV 文件 : no implicit conversion of StringIO into String

mysql - 我可以将 MAMP (MySQL) 或 XAMPP (MySQL) 与 Ruby on Rails 3 一起使用吗?

MySQL 搜索多列,但强制执行一个条件

android - 使用 Android 连接到远程 MySQL 数据库

mysql - jpql select查询与where子句不区分非英文字符