如何通过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
答案 0 :(得分:5)
尝试更明确地返回,例如那样:
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
答案 1 :(得分: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错误的原因。