1

我现在有一个简单的搜索表单,它将在我的模型中搜索一列并按预期返回结果,但是我希望通过能够使用 4 个 text_field/Select_tags 搜索同一模型中的 4 列来建立此基础。

例如,我查看了提供类似 solr 的 Gems,但我的想法是,对于我想要实现的目标来说,这似乎有点矫枉过正,尤其是在这么小的应用程序上

该应用程序很简单,您可以上传食谱,将食谱添加到收藏夹和搜索食谱。

到目前为止,它看起来像这样

控制器

 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 %>

只是一些正确方向的指针将不胜感激。谢谢

4

1 回答 1

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
于 2012-11-09T10:02:43.503 回答