Rails:嵌套表单内的嵌套字段

问题描述 投票:0回答:1

我具有以下三个模型和关联:

class ParentProduct < ApplicationRecord
  has_many :child_products
  accepts_nested_attributes_for :child_products, allow_destroy: true
  has_many :attachments, dependent: :destroy
  accepts_nested_attributes_for :attachments, allow_destroy: true
end

class ChildProduct < ApplicationRecord
  belongs_to :parent_product
  has_many :attachments, dependent: :destroy
  accepts_nested_attributes_for :attachments, allow_destroy: true
end

class Attachment < ApplicationRecord
  belongs_to :parent_product, optional: true
  belongs_to :child_product, optional: true
  mount_uploader :image, AttachmentUploader
end

此设置的目的是创建带有附件的父产品。而且,如果用户愿意,他可以创建子产品及其附件并将其与该父产品相关联。

在新的parent_products_controller中,我具有以下设置,以便最初添加8个附件字段。另外我也不想一开始显示child_product_fields,这就是为什么我没有添加此@parent_product.child_products.build

def new
  @parent_product = ParentProduct.new
  8.times{ @parent_product.attachments.build }
end

在创建父产品的表单中,我具有附件嵌套字段,以便为父产品创建附件。当用户单击add a product variation link时,它会打开child_product_fields

<%= simple_form_for @parent_product, url: parent_product_path, method: :post, validate: true do |f| %>

  <%= f.simple_fields_for :attachments do |attachment| %>
    <%= render 'parent_products/attachment_fields', form: attachment  %>
  <% end %>

  <%= f.simple_fields_for :child_products do |child_product| %>
    <%= render 'parent_products/child_product_fields', form: child_product %>
  <% end %>

  <div class="links float-right" style="margin-bottom: 30px;">
     <%= link_to_add_association raw('<i class="far fa-plus-square"></i> Add a product variation'), f, :child_products, form_name: 'form', :style=>"color: grey; font-size: 14px;" %>
   </div>
<% end %>

现在在child_product_fields内部,我还有一个附件嵌套字段,以便为子产品创建附件。

<%= form.simple_fields_for :attachments do |attachment| %>
  <%= render 'parent_products/attachment_fields', form: attachment  %>
<% end %>

现在的问题是,当我单击并打开child_product_fields时,无法显示8个附件字段。我需要的设置是...。当我单击并打开child_product_fields时,还将出现8个附件字段。关于如何实现这一点的任何想法吗?

ruby-on-rails cocoon-gem
1个回答
1
投票

您可以使用:wrap_objectlink_to_add_association选项。它允许在渲染嵌套表单之前添加额外的初始化。因此,在您的情况下,您可以为一个子产品添加8个附件。

例如做类似的事情>>

<div class="links float-right" style="margin-bottom: 30px;">
  <%= link_to_add_association raw('<i class="far fa-plus-square"></i> Add a product variation'), 
        f, :child_products, form_name: 'form',
        wrap_object: Proc.new {|child| 8.times {child.attachments.build }; child }, 
        style: "color: grey; font-size: 14px;" %>
</div>
    
© www.soinside.com 2019 - 2024. All rights reserved.