如何按多个参数进行搜索/过滤,这些参数在 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
尝试更明确地返回,例如:
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
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 的错误。