在 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
关于ruby-on-rails - 在 Rails 3 中使用多个可选的 where 条件(子句)进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14576520/