Rails 茧嵌套字段,在编辑表单上呈现每个字段旁边的现有图像

Rails cocoon nested fields, on edit form render existing images next to each field

我正在使用 cocoon gem 向产品添加附件。这是我在新产品表单中渲染茧嵌套表单字段的部分。

<div id="attachments">
   <%= f.label :images, required: true %>
    <%= render 'products/attachment_fields', form: attachment  %>
    <% end %>

     <div class="links" id="add_attachment" style="display: inline; float: right;">
       <%= link_to_add_association 'add more images', f, :attachments, form_name: 'form' %>
     </div>
 </div>

这是部分:

<div class="nested-fields">
  <span class="control-fileupload">
    <%= form.input :images,:label => "Choose a file", as: :file, :input_html => { class: "file_input" } %>
  </span>
  <%= link_to_remove_association "remove", form %>
</div>

以上所有操作都很好。产品也与附件一起创建。

现在我正在尝试开发编辑产品表单,我可以在其中编辑产品和附件。这个也一切正常。我遇到的唯一麻烦是......如何将每个现有附件图像添加到编辑表单中的关联茧嵌套字段???目前只有字段显示,用户不知道哪个字段包含什么图像,因此他可以根据需要进行更改。我尝试了以下操作,图像在每个字段上都正确显示,但每个现有字段都渲染了两次:

<div id="attachments">
   <%= f.label :images, required: true %>
      <%= f.simple_fields_for :attachments do |attachment| %>
        <% if @attachments.present? %>
          <% @attachments.each do |attached| %>
            <%=image_tag attached.images_url(:thumb).to_s %>
            <%= render 'retailer_products/attachment_fields', form: attachment  %>
           <% end %>
         <% end %>
      <% end %>
          <div class="links" id="add_attachment" style="display: inline; float: right;">
            <%= link_to_add_association 'add more images', f, :attachments, form_name: 'form' %>
          </div>
  </div>

在您的 attachment_fields 部分中,添加这些行以显示图像

<% if form.object.persisted? %>
    <%= image_tag form.object.images_url(:thumb).to_s %>  ## form.object will return your attachment object, from this you can access your image
<% end %>

您的现有字段呈现多次,因为您在 attachmentseach 循环中多次呈现嵌套字段。

将您的 div id="attachments" 还原为:

<div id="attachments">
   <%= f.label :images, required: true %>
    <%= render 'products/attachment_fields', form: attachment  %>
    <% end %>

     <div class="links" id="add_attachment" style="display: inline; float: right;">
       <%= link_to_add_association 'add more images', f, :attachments, form_name: 'form' %>
     </div>
 </div>