如何在模型的多个字段中有效地进行搜索?
# 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,则它不会返回结果。有没有更优雅的方式?
最佳答案
我认为这确实有效
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'
关于ruby-on-rails - 使用 will_paginate/searchlogic 搜索多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4176650/