多字用Ruby搜索和MySQL [英] Multiple word searching with Ruby, and MySQL

查看:128
本文介绍了多字用Ruby搜索和MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图完成一个多字搜索中使用Ruby,ActiveRecord的和MySQL数据库的报价。我做的方式显示波纹管,它的工作,但我想知道是否有更好的方法来做。

I'm trying to accomplish a multiple word searching in a quotes database using Ruby, ActiveRecord, and MySQL. The way I did is shown bellow, and it is working, but I would like to know if there a better way to do.

# 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

我想知道是否有更好的方法来组成这个条件的字符串。我也尝试过使用字符串插值,例如,使用*运算符,但最终需要更多的字符串处理。在此先感谢

I would like to know if there is better way to compose this 'conditions' string. I also tried it using string interpolation, e.g., using the * operator, but ended up needing more string processing. Thanks in advance

推荐答案

首先,我强烈建议您型号的逻辑进入模型。而不是创建搜索逻辑到控制器,创建一个#search方法到您的报价模式。

First, I strongly encourage you to move Model's logic into Models. Instead of creating the search logic into the Controller, create a #search method into your Quote mode.

class Quote
  def self.search(query)
    ...
  end
end

和您的控制器将成为

# 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

现在,回到原来的问题。您现有的搜索逻辑做一个非常严重的错误:它直接插值打开您的code SQL注入。假设你使用的Rails 3,您可以利用新的#where语法。

Now, back to the original problem. Your existing search logic does a very bad mistake: it directly interpolates value opening your code to SQL injection. Assuming you use Rails 3 you can take advantage of the new #where syntax.

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 + 注射呢,我建议你阅读文章<一个href="http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/">The瘦的作用域。

It's a little bit of advanced topic. I you want to understand what the combined_scope + inject does, I recommend you to read the article The Skinny on Scopes.

这篇关于多字用Ruby搜索和MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆