【问题标题】:How can I create a search form with check boxes in Ruby on Rails?如何在 Ruby on Rails 中创建带有复选框的搜索表单?
【发布时间】:2016-01-07 03:58:03
【问题描述】:

假设我有食谱和配料,所以有一个关系 n:m。

好的,一切正常,关系有效,我有一个名为 ingredients_recipe 的联接表及其存储配方 ID 和数据库中每个配方的成分 ID。

现在,我想创建一个搜索表单,您可以在其中选择成分,然后显示包含这些成分的食谱。

例如:

我选择土豆、番茄和米饭,所以它应该显示包含这些成分的食谱。

【问题讨论】:

  • 那么你现在的问题是什么?
  • 查看Railscastthis one。当您遇到特定编程问题时再次发布。就目前而言,您要求的教程超出了 Stack Overflow 的范围。

标签: ruby-on-rails ruby search


【解决方案1】:

请找到以下视图以及搜索代码:

查看:

  <%= form_tag (search_url) do %>
    <% @ingredients.each do |ing| %>
      <%= check_box_tag "ingredient_ids[]", ing.id, id: => "ingredient_ids_#{ing.id}" %>
    <% end %>
    <%= submit_tag "Search" %>
  <% end %>

控制器:

def search
  @recipes = Recipe.joins(:ingredients_recipes).where(
    ingredients_recipes: { ingredient_id: params[:ingredient_ids] } 
  )
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2013-05-29
    • 2017-07-11
    • 2011-02-05
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多