【问题标题】:Rails - Form accessing items in a db tableRails - 表单访问数据库表中的项目
【发布时间】:2014-04-16 20:08:37
【问题描述】:

我正在创建一个 Rails 食谱应用程序,当用户创建新食谱时,他们必须添加成分。我在数据库中有一个食物表(关于食物的其他属性意味着我需要另一个表)。它需要是多对多的关系,因为食谱有多种成分,但食物可以在多个食谱中。我创建了一个表recipes_ingredients,以帮助处理这种多对多关系。我遇到的问题是新食谱的形式。用户应该只能使用食物表中的食物。我想做谷歌在其搜索中所做的下拉选项。这是我能想到的最好的方法。你们中有人对如何做到这一点有想法吗?对于如何在食谱中添加成分,您还有其他想法吗?

我使用的是 rails 4.1 和 ruby​​ 2.1。我在 Ubuntu 12.04 上。

【问题讨论】:

    标签: ruby-on-rails database forms many-to-many


    【解决方案1】:

    您可以使用部分添加成分(从成分表中获取成分并将其存储在您的 recipes_ingredients 表中)。

    在食谱表单中添加部分渲染

    <%= f.fields_for :recipesingredients do |ff| %>
        <ol>
            <table id = "tabla">
                <tr>
                    <td style = "padding-left: 8px"><%= render 'recipesingredients_fields', :f => ff %></td>
                </tr>
            </table>
        </ol>
    <% end %>
    <div id = "ingredientsadd"></div>
    <%= link_to_add_association 'Add', f, :recipesingredients, 'data-association-insertion-node' => "#ingredientsadd", 'data-association-insertion-method' => "append" %>
    

    然后,在该部分中,您可以将要添加的字段添加到 recipes_ingredients 表中。在这种情况下,我假设您只需要成分 ID。在这种情况下,您将使用 options_from_collection 标记来填充当前存储在成分表中的值。

    <%= f.select :ingredient_id , options_from_collection_for_select(@ingredients, :id, :name)%>
    

    请记住,您的 recipes_ingredients 需要有一个 recipe_id 和一个 ingredients_id 字段。此外,成分必须属于_recipe,并且recipe 必须有_many 成分。

    希望这会有所帮助!

    【讨论】:

    • 抱歉这么久才回复您。这很有帮助!只有几件事需要澄清......出于某种原因,行 引发错误,“未定义的方法 `map' for nil: NilClass"....知道那是什么意思吗?
    • 这意味着您尝试“映射”的“集合”是空的。你在成分表中有什么价值吗? @ingredients(在我的示例中)应该将所有值存储在成分模型中(@ingredients = Ingredient.all)。
    • 我的表中确实有配料,但我最终改变了为我的应用程序制作配料的方式
    • 哦,好吧,如果您更改它,那么我提供的答案可能不再适合您。祝你好运。
    猜你喜欢
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多