Ruby on Rails - 基于查询在数据库中搜索

时间:2012-12-03 14:26:29

标签: sql ruby-on-rails ruby activerecord sql-like

我有一个简单的表单,我在其中设置了一个我想要浏览的查询,例如 panasonic viera 。 这是关于我在数据库中搜索术语的方式:

Product.where("name ilike ?", "%#{params[:q]}%").order('price')

查询看起来像%panasonic viera%,但我需要以这种方式搜索查询:%panasonic%viera% - 我需要查找所有产品,标题中的单词 panasonic viera ...但是如何进行此查询?

4 个答案:

答案 0 :(得分:3)

一种解决方案是将查询分解为单个术语,并构建一组由OR连接的数据库查询。

terms = params[:q].split
query = terms.map { |term| "name like '%#{term}%'" }.join(" OR ")
Product.where(query).order('price')

答案 1 :(得分:1)

如果您正在使用PostgreSQL,则可以使用pg_search gem。它支持全文搜索,选项any_word

Setting this attribute to true will perform a search which will return all models containing any word in the search terms.

来自pg_search的示例:

class Number < ActiveRecord::Base
  include PgSearch
  pg_search_scope :search_any_word,
                  :against => :text,
                  :using => {
                    :tsearch => {:any_word => true}
                  }

  pg_search_scope :search_all_words,
                  :against => :text
end

one = Number.create! :text => 'one'
two = Number.create! :text => 'two'
three = Number.create! :text => 'three'

Number.search_any_word('one two three') # => [one, two, three]
Number.search_all_words('one two three') # => []

答案 2 :(得分:1)

通过ARel

怎么样
def self.search(query)
  words      = query.split(/\s+/)
  table      = self.arel_table
  predicates = []

  words.each do |word|
    predicates << table[:name].matches("%#{word}%")
  end

  if predicates.size > 1
    first = predicates.shift
    conditions = Arel::Nodes::Grouping.new(predicates.inject(first) {|memo, expr| Arel::Nodes::Or.new(memo, expr)})
  else
    conditions = predicates.first
  end

  where(conditions).to_a
end

答案 3 :(得分:0)

这不起作用?

 WHERE name LIKE "panasonic" OR name LIKE "viera"