我具有以下三个模型和关联:
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个附件字段。关于如何实现这一点的任何想法吗?
您可以使用:wrap_object的link_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>