如何有效地搜索模型中的许多字段?
# 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来自:代码,它不会返回结果。有更优雅的方式吗?
答案 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'