[英]Ruby on Rails - search in database based on a query
我有一個簡單的表單,可以在其中設置要瀏覽的查詢,例如panasonic viera 。 這是關於我如何在數據庫中搜索術語的方法:
Product.where("name ilike ?", "%#{params[:q]}%").order('price')
查詢看起來像%panasonic viera% ,但是我需要以這種方式搜索查詢: %panasonic%viera% -我需要找到所有產品,標題中的單詞panasonic或viera ...在哪里 ,但是如何制作這個查詢?
一種解決方案是將查詢分解為單獨的術語,並建立一組通過OR
連接的數據庫查詢。
terms = params[:q].split
query = terms.map { |term| "name like '%#{term}%'" }.join(" OR ")
Product.where(query).order('price')
如果您使用的是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') # => []
如何通過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
這不行嗎?
WHERE name LIKE "panasonic" OR name LIKE "viera"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.