3

如何通过 Rails 3.2 中每个可选的多个参数进行搜索/过滤?通过以下设置,我目前收到以下错误。任何帮助是极大的赞赏。

undefined method `paginate' for nil:NilClass

Application Trace | Framework Trace | Full Trace
app/controllers/contacts_controller.rb:50:in `index'

这是我的 contacts_controller 中的索引操作:

def index
  city = params[:city]
  state = params[:state]
  zip = params[:zip]
  @contacts = Contact.search(city,state,zip).paginate(:page => params[:page], :per_page => items_per_page)
end

这是我的联系人模型中的搜索方法:

def self.search(city, state, zip)
  joins(:profile => :addresses)
  .where("city like ?", "%#{city}%") unless city.blank?
  .where("state = ?", state) unless state.blank?
  .where("zip like ?", "%#{zip}%") unless zip.blank?
end
4

2 回答 2

7

尝试更明确地返回,例如:

def self.search(city, state, zip)
  query_obj = joins(:profile => :addresses)
  query_obj = query_obj.where("city like ?", "%#{city}%") unless city.blank?
  query_obj = query_obj.where("state = ?", state) unless state.blank?
  query_obj = query_obj.where("zip like ?", "%#{zip}%") unless zip.blank?

  query_obj
end
于 2013-01-29T05:59:23.290 回答
0
def self.search(city, state, zip)
  conditions = {:"city like %?%" => city, :state => state, :"zip like %?%" => zip}
  conditions.delete_if {|key,val| val.blank? }
  self.joins(:profile => :addresses)
  .where(conditions)
end

并且您的函数 Contact.search(city,state,zip) 返回nil,这就是它给出 nil.paginate 错误的原因。

于 2013-01-29T06:06:53.377 回答