轨道:嵌套表单内的嵌套字段



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

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个附件字段。关于我如何实现这一点的任何想法?

您可以使用link_to_add_association的 :wrap_object 选项。它允许在呈现嵌套表单之前添加额外的初始化。因此,在您的情况下,您可以向子产品添加 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>

最新更新