2010-05-11 80 views
0

我在Products模型中有一個下拉列表Type紅寶石搜索下拉菜單

我希望能夠在Products index.html.erb中進行搜索,以便用戶從下拉列表中選擇一種類型,單擊搜索並返回所有匹配該類型的產品。

我可以在正常的搜索方法中工作,用戶在文本框中輸入他們的搜索內容,但是當他們從下拉列表中選擇時,我無法使其工作。

任何人都可以幫忙嗎?

+0

寧願這樣做,而無需添加更多插件 – user338454 2010-05-11 16:16:20

回答

1

在你的控制器:

def index 
    @products = Product.all :conditons => {:type => params[:type]} 
end 

在視圖:

<% form_tag products_path, :method => :get do %> 
    <%=select_tag :type, options_for_select(Product::TYPES.map{ |type| [type, type]}), :onchange => "this.form.submit();" %> 
    <%=submit_tag "Search" %> 
<% end %> 

NB:本options_for_select接受對數組作爲[標號,值],因此我們使用圖來建立它。

+0

我將產品類型存儲爲字符串。 在產品模型中,我爲 TYPES = [「type1」,「type2」] – user338454 2010-05-11 16:27:37

+0

設置類型的選項而我發佈的代碼不起作用?它會給你一個錯誤? – 2010-05-11 16:29:42

+0

我的問題是我不能得到它實際上搜索,因爲我不知道如何與下拉,這是我在index.html.erb find type <%= select(「product」, 「type」,Product :: TYPES)%> <%= submit_tag「Search」,:name =>「submit_search」,:class =>「button」%> – user338454 2010-05-11 16:35:47