2014-12-03 33 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