Ruby on Rails – 基于查询在数据库中搜索
我有一个简单的表单,我在其中设置了一个我想浏览的查询,例如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"
- 如何使用Ruby on Rails查找今天,昨天等的记录?
- 回调更改的ActiveRecord属性?
- find_or_create_by_id的最佳方法,但如果找到记录则更新属性
- 使用ActiveRecord和Rails将数据插入postgresql数据库会出现此错误:RuntimeError:ERROR C22003 Minteger o
- 使用ruby和active_record保存时的DEPRECATION WARNING
- 如何使用has_many:through保存数据
- 在heroku上插入数据库错误但在本地工作,ActiveRecord :: StatementInvalid
- 错误:表“用户”上的更新或删除违反表“评论”上的外键约束“fk_rails_03de2dc08c”
- 如何使用ActiveRecord列出所有数据库