2

您如何有效地在模型中的多个字段中进行搜索?

# 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来自:name而单词#2来自:code,它不会返回结果。有没有更优雅的方式?

4

3 回答 3

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'
于 2010-11-14T08:11:17.017 回答
1

您可以使用搜索逻辑

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

希望你有这个想法

于 2010-12-21T06:20:31.610 回答
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' 
于 2010-11-14T14:05:53.993 回答