我试图创建简单的搜索引擎,但我遇到了一些问题。我的表单中有几个search_field,如果两者都是空的,应该返回所有对象。否则,当它有任何内容时,应该由该内容来选择。以下是我的表格样本:
<%= form_for :product, url: products_path, method: :get do |form| %>
<%= form.search_field :brand %>
<%= form.search_field :model %>
<%= form.search_field :price_from %>
<%= form.search_field :price_to %>
<%= form.submit 'Submit' %>
<% end %>我的模型方法:
def self.search(search)
where(brand: search[:brand]).where(model: search[:model]).where("price >= ?", search[:price_from]).where("price <= ?", search[:price_to])
end但是上面的代码是错误的,因为如果我让某个字段为空,它将被直接视为空字符串,而不是忽略该字段,并且最终结果是不正确的。此表单的工作方式类似于在线商店的筛选。
发布于 2015-10-22 22:16:55
你可以做这样的事
def self.search(search)
results = all
results = results.where(brand: search[:brand]) if search[:brand]
results = results.where(model: search[:model]) if search[:model]
results = results.where("price >= ?", search[:price_from]) if search[:price_from]
results = results.where("price <= ?", search[:price_to]) if search[:price_to]
return results
end祝好运。
https://stackoverflow.com/questions/33291377
复制相似问题