Rails:文件嵌套字段,显示每个字段上选中的文件名

Rails: file nested fields, show the name of file selected on each field

我正在使用 cocoon gem 来添加带有嵌套字段的图像:

<div id="attachments">
    <%= f.simple_fields_for :attachments do |attachment| %>
    <%= 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>

这是部分.... _attachment_fileds.tml.erb:

<div class="nested-fields">
  <%= form.label :image, required: true %>
    <div class="input-group">
      <div class="custom-file" style="padding-top: 38px;">
        <%= form.input :images, label: false, as: :file, :input_html => { :class => 'custom-file-input', :style=>"cursor: pointer", :id=>"inputGroupFile01"} %>
        <label class="custom-file-label" for="inputGroupFile01" id="file-name" style="cursor: pointer;">Choose file</label>
      </div>
    </div>
       <div style="text-align: right;"><%= link_to_remove_association "remove", form %></div>
</div>

一切正常。

现在,对于使用 cocoon 生成的每个字段,我想用所选文件的名称替换标签字段中的 choose a file 文本。

起初我尝试了以下方法,但后来我发现 cocoon gem 为每个字段生成了不同的 ID。

<script>
  $("#inputGroupFile01").change(function(){
      $("#file-name").text(this.files[0].name);
  });
</script>

所以现在我有点卡在如何实现上面的问题上了。非常感谢任何帮助。

html-id 在页面上应该是唯一的,因此您不能对重复字段使用唯一的 id。虽然页面可能会正确呈现,但当 post 编辑表单时,它将忽略重复的 ID(因此会 post incorrect/incomplete 信息)。

其次,使用jquery很容易找到最近的元素。

所以在你的部分嵌套字段中删除所有 id,所以写类似

<%= form.input :images, label: false, as: :file, 
      :input_html => { :class => 'custom-file-input', :style=>"cursor: pointer"} %>
<label class="custom-file-label" style="cursor: pointer;">Choose file</label>

然后你可以写类似的东西(显然未经测试)

$(".nested-fields .custom-file-input").change(function(){
  $(this).siblings("label.custom-file-label").text(this.files[0].name);
});

有几个选项,我不确定哪个 selector 效果最好。您可以上去,然后 select 正确的标签:

 $(this).closest('.nested-fields').find('label.custom-file-label') 

我不确定只查找 closest 标签是否可行?

 $(this).closest('label.custom-file-label') 

或者像我上面那样,用正确的 select 或寻找 sibling