2014-12-03 60 views
0

我使用多个下拉菜单创建搜索,并且他们在提交'',如果用户没有选择一个。我需要一个catchall,像SQL中的*作为默认值。即如果我在一个下拉列表中有5个品牌,我希望默认查询为全部5个品牌。像Brand.where(品牌:ALL)。提前致谢。提交导轨时忽略空白字段

<%= select_tag(:brand, options_for_select(["Brand 1","Brand 2","Brand 3","Brand 4","Other"].map{ |num| [num,num] }),id: 'brand', prompt: 'Brand', class: "table") %> 
+0

你到目前为止的任何例子? – DickieBoy 2014-12-03 16:49:10

+0

<%= select_tag(:brand,options_for_select([“Brand 1”,“Brand 2”,“Brand 3”,“Brand 4”,“Other”]。 id:'brand',提示:'Brand',class:“table”)%>就是一个例子。 所以默认值是品牌,我希望选定的值是ALL,所以它实际上不过滤任何东西。 – 2014-12-03 16:50:07

+0

您可以为“all”制作另一个选项,并将选项分配给控制器中您想要的属性?当create()将品牌参数选择为'all'时,将其指定为保存前的方式。 – DDDD 2014-12-03 16:52:26

回答

0

你可能想include_blank,并在您选择prompt

select_tag(..., include_blank: true, prompt: 'All') 

现在下拉菜单中的第一个条目将有一个空白值,并为其标签显示“全部”。

然后,您只是需要确保当您查询,这样的事情你不要使用标准(你没有张贴任何代码,所以我不知道你的模型):

class MyController ... 

    def show 
    @items = Item.all 
    @items = @items.where(brand: params[:brand]) if params[:brand].present? 
    @items = @items.where(size: params[:size]) if params[:size].present? 
    @items = @items.where(year: params[:year]) if params[:year].present? 
    @items = @items.where(color: params[:color]) if params[:color].present? 
    end 

end 
+0

现货 - 我太过于复杂。谢谢 – 2014-12-03 17:09:48

1

如何像:

product.rb

class Product < ActiveRecord::Base 
    scope :by_brand, -> (brand) { where brand: brand } 
    # put more scopes for the other drop-down boxes 
end 

product_controller.rb

class ProductsController < ApplicationController 
    def search 
    @products = Product.all 
    @products = @products.by_brand(params[:brand]) unless params[:brand].blank? 
    # more filtering here 
    end 
end