سؤال

What I currently have is:

<%= f.label :attachment_uploader, 'Current Attachments:' %>
<%= f.fields_for :data_files do |attachment| %>
   <% if !attachment.object.new_record? %>
      <%= attachment.label :attachment_uploader, 'Delete: ' + attachment.object.attachment_uploader_url.split("/").last %>
      <%= attachment.check_box :_destroy %>
    <% end %>
<% end %>

However, if I don't have any attachments the label is still there. For the sake of aesthetics I'd like it to be hidden unless I have attachments.

I was thinking something akin to:

<%= f.fields_for :data_files do |attachment, index| %>
  <% if index == 0 %>
     <%= attachment.label :attachment_uploader, 'Current Attachments:' %>
  <% end %>
  #rest of code
<% end %>

But that doesn't work!

I've read about the f.options[:index] in another post, but I couldn't figure it out.

هل كانت مفيدة؟

المحلول

Add an unless empty? condition before fields_for. @object will be the object for which you created the form

<%= f.label :attachment_uploader, 'Current Attachments:' %>
<% unless @object.data_files.empty? %>
    <%= f.fields_for :data_files do |attachment| %>
       <% if !attachment.object.new_record? %>
          <%= attachment.label :attachment_uploader, 'Delete: ' + attachment.object.attachment_uploader_url.split("/").last %>
          <%= attachment.check_box :_destroy %>
        <% end %>
    <% end %>
<% end %>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top