标签只在fields_for中出现一次

时间:2014-02-24 01:49:51

标签: ruby-on-rails ruby nested-forms

我目前拥有的是:

<%= 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 %>

但是,如果我没有附件,标签仍然存在。为了美学,除非我有附件,否则我希望它被隐藏起来。

我在想类似的事情:

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

但这不起作用!

我在另一篇文章中读过f.options[:index],但我无法理解。

1 个答案:

答案 0 :(得分:1)

unless empty?之前添加fields_for条件。 @object将是您为其创建表单的对象

<%= 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 %>