2012-11-09 35 views
1

我現在有一個簡單的搜索表單,它將搜索我的模型中的一列,並按照預期返回結果,但是我希望能夠在同一列內搜索4列模型,使用4個text_field/Select_tags。在模型導軌中搜索多列3

我已經看過提供這種類似SOLR例如寶石,但我的想法是,它似乎什麼我想要實現一個有點矯枉過正,特別是在這樣一個小的應用程序

應用程序很簡單,你可以上傳食譜,將食譜添加到收藏夾和搜索食譜。

到目前爲止,它看起來像這樣

控制器

def search 
@countrysearch = Recipe.where(:country_of_origin => params[:search]).all 
end 

搜索表單

<%= form_tag({:controller => 'search', :action => 'search'}, {:method => 'get'}) do |s| %> 
<%= text_field_tag :search, params[:search] %> 
<%= submit_tag "Search" %> 
<% end %> 

輸出(查看)

<% @countrysearch.each do |r| %> 
    <tr> 
    <td><%= r.dish_name %></td> 
    <td><%= r.country_of_origin %></td> 
    <td><%= r.difficulty %></td> 
    <td><%= r.preperation_time %></td> 
    <td><%= ingredient_names(r.ingredients) %></td> 
    <td><%= preperation_steps(r.preperations) %></td> 
</tr> 

我想我的搜索形式鏡我的「創建新配方形式」與選擇標籤

<%= f.label :dish_name, "Dish Name" %> 
    <%= f.text_field :dish_name, :placeholder => "Enter Dish Name" %> 

    <%= f.label :country_of_origin, "Country Of Origin" %> 
    <%= f.select :country_of_origin, [['Wales'],['Scotland'],['England']], {:include_blank => 'Please Select'} %> 

    <%= f.label :difficulty, "Difficulty Level" %> 
    <%= f.select :difficulty, [['Beginner'],['Intermediate'],['Expert']], {:include_blank => 'Please Select'} %> 


    <%= f.select :preperation_time, [['15..30'],['30..60'],['60..120']], {:include_blank => 'Please Select'} %> 


<% end %> 

只是在正確的方向一些指針將不勝感激。謝謝

回答

2

則可以使用你傳遞給控制器​​的所有參數做:

def search 
@countrysearch = Recipe.where({:dish_name => params[:search][:dish_name], :country_of_origin => params[:search][:country_of_origin], :difficulty => params[:search][:difficulty], :preperation_time => params[:search][:preperation_time]}).all 
end 

這應該爲你工作。還有其他的選擇,但如果你想要一個簡單的,這可能適合你。

編輯:

如果您沒有在您的搜索別的事情,你可以做這樣的事情:

<%= form_tag({:controller => 'search', :action => 'search'}, {:method => 'get'}) do |s| %> 
<%= text_field_tag :dish_name, params[:dish_name] %> 
<%= select_tag "country_of_origin", options_from_collection_for_select(@recipes, "country_of_origin", "country_of_origin_name") 
<%= select_tag "difficulty ", options_from_collection_for_select(@recipe, "difficulty ", "difficulty ") 
<%= select_tag "preperation_time", options_from_collection_for_select(@recipe, "preperation_time", "preperation_time") 
<%= submit_tag "Search" %> 
<% end %> 

然後在controlelr只是傳遞的參數直接

def search 
@countrysearch = Recipe.where(params).all 
end 
+0

非常感謝,我已經看到另一個看起來與你相似的例子,唯一不同的是你指定[:dish_name]作爲例子的一部分PARAMS?所以不要傳遞你傳遞的參數[:search] [:search] [:dish_name]。通過這個額外的參數實現什麼?將有興趣知道作爲新的軌道...再次雖然感謝您的回答 – Richlewis

+0

我通過params [:dish_name],因爲它使您可以在每個參數中傳遞不同的值散列項目。每個子句一個。我用另一種方法更新了回覆,你可以試試,因爲我沒有在這裏的鐵軌! – felipeclopes

+0

啊我看到了,謝謝 – Richlewis