使用will_paginate / searchlogic搜索许多字段

时间:2010-11-14 07:55:08

标签: ruby-on-rails ruby-on-rails-3 will-paginate searchlogic

如何有效地搜索模型中的许多字段?

# user.rb model
def self.search(search, page)  
  paginate :per_page => 20, :page => page,
  :conditions => 
    ['name like ? OR notes like ? OR code like ? OR city like ? OR state like ?,
    "%#{search}%","%#{search}%","%#{search}%","%#{search}%","%#{search}%"
    ], :order => 'name'

这个代码对于任何一个以上的字段都是可怕的,并且如果单词#1来自:名称和单词#2来自:代码,它不会返回结果。有更优雅的方式吗?

3 个答案:

答案 0 :(得分:2)

我认为这样做

def self.search(search, page)
  fields = [:name, :notes, :code, :city, :state] 
  paginate :per_page => 20, :page => page,
  :conditions => [fields.map{|f| "#{f} like ?"}.join(' OR '),
    *fields.map{|f| "%#{search}%"}], :order => 'name'

答案 1 :(得分:1)

您可以使用searchlogic

def self.search(search, page)  
  search_cond = resource.search(name_or_notes_or_code_or_city_or_state_like => search.to_s)
  search_cond.all
end

希望你有这个想法

答案 2 :(得分:0)

def self.search(search, page)
  fields = %w(name notes code city state) 
  paginate :per_page => 20, :page => page,
  :conditions => [fields.map{|f| "#{f} like :phrase"}.join(' OR '), {:phrase => search}], 
  :order => 'name'