【问题标题】:Rails cocoon nested fields, on edit form render existing images next to each fieldRails 茧嵌套字段,在编辑表单上呈现每个字段旁边的现有图像
【发布时间】:2019-03-14 09:17:48
【问题描述】:

我正在使用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>

【问题讨论】:

    标签: ruby-on-rails cocoon-gem


    【解决方案1】:

    在您的 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多