【问题标题】:Cocoon nested form not showing in Rails 5茧嵌套形式未在 Rails 5 中显示
【发布时间】:2018-08-17 11:50:23
【问题描述】:

我有一个模型配方和一个模型成分。配方 has_many :ingredients 和成分 belongs_to :recipe。 我正在使用 Cocoon 和 Simple Forms 创建嵌套表单。 主窗体正在工作和显示,但由于某种原因嵌套窗体没有呈现。 知道为什么吗?

模型

class Recipe < ApplicationRecord
    has_many :ingredients
end

class Ingredient < ApplicationRecord
    belongs_to :recipe
end

配方控制器(参数)

    def recipe_params
        params.require(:recipe).permit(:title, :description, :image, 
        ingredients_attributes: [:id, :name, :_destroy], 
        directions_attributes: [:id, :step, :_destroy])
    end

查看

<%= simple_form_for @recipe do |f| %>
    <div class="field">
        <h3>Recipe</h3>
        <%= f.input :title %>
        <%= f.input :description %>
        <%= f.input :image, as: :file %>

        <div id="ingredients">
            <h3>Ingredients</h3>

            <%= f.simple_fields_for :ingredients do |ingredient| %>
                    <p>ajsd</p>
                <%= render 'ingredients_fields', f: ingredient %>

                <%= link_to_add_associtation 'Add Ingredient', f, :ingredients %>
            <% end %>

        </div>

        <%= f.button :submit, class: "button button-highlight button-block" %>
    </div>
<% end %>

div#ingredients 中的 simple_forms 未呈现。

【问题讨论】:

    标签: ruby-on-rails model-view-controller simple-form nested-forms cocoon-gem


    【解决方案1】:

    您的嵌套字段表单显示有以下代码:

    <%= f.simple_fields_for :ingredients do |ingredient| %>
      <p>ajsd</p>
      <%= render 'ingredients_fields', f: ingredient %>
      <%= link_to_add_associtation 'Add Ingredient', f, :ingredients %>
    <% end %>
    

    simple_fields_for 中的代码对@recipe 中的每种成分执行一次(如果@recipe 没有任何成分,则不会显示)。

    我猜你正在创建一个空食谱。您可以做的是在新方法中向配方中添加一个空成分:

    @recipe.ingredients.build
    

    这将在表单中显示一个空食谱。

    另一个重要问题是link_to_add_association(在您的 OP 中有错字)在 simple_fields_for 内。它必须在外面,以便在最后显示,即使没有任何成分。

    最后,你也不见了:

    accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
    

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多