如何在单击link_to_add_association后显示关联字段?

时间:2017-09-03 20:25:49

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

大家好,我正在使用非常有用的宝石:https://github.com/nathanvda/cocoon

我的目标是仅在我点击link_to_add_association时显示我的关联字段。

我加载表单页面时不应显示字段。

有谁知道怎么做?

干杯

文件部分

<h4><%= t('.title') %></h4>

<ul class="documents-list">
  <%= f.fields_for :property_documents do |property_document_fields| %>
    <% unless property_document_fields.object.new_record? %>
      <%= render '/shared/properties/property_documents_list', f: property_document_fields %>
    <% end %>
  <% end %>
</ul>

<ul class="list-group property-documents">
  <%= f.fields_for :property_documents do |property_document_fields| %>
    <% if property_document_fields.object.new_record? %>
      <%= render '/shared/properties/property_document_fields', f: property_document_fields %>
    <% end %>
  <% end %>
</ul>

<span class="pull-left">
  <%= link_to_add_association t('.add_document'),
                              f,
                              :property_documents,
                              partial: 'shared/properties/property_document_fields',
                              class: 'btn btn-primary',
                              data: {
                                association_insertion_node: '.property-documents',
                                association_insertion_method: :append
                              } %>
</span>

文件字段

<li>
  <%= link_to admin_property_path(@property.id, property: { property_documents_attributes: { id: f.object.id, "_destroy" => true }}), remote: false, confirm: "Really delete #{f.object.name} ?", method: :put do %>
    <i class="fa fa-trash" style="padding-right: 10px; color: #d9534f;"></i>
  <% end %>
  <% if f.object.document.present? %>
    <%= link_to f.object.name, f.object.document.url, target: :_blank %>
  <% else %>
    <%= link_to f.object.name, url_with_protocol(f.object.url), target: :_blank %>
  <% end %>
</li>

2 个答案:

答案 0 :(得分:0)

默认情况下,Cocoon不会生成嵌套关联。也许你这样做你的文档模型或控制器,如

document.property_documents.build

答案 1 :(得分:0)

在尝试了很多东西之后,我发现了这个解决方案...

从控制器

中的编辑方法中删除property_photos.build

并在表单中,让它像:

<ul class="list-group property-photos">
  <%= f.fields_for :property_photos do |property_photo_fields| %>
    <% if property_photo_fields.object.new_record? %>
      <%= render '/shared/properties/photos/property_photo_fields', f: property_photo_fields %>
    <% end %>
  <% end %>
</ul>

欢呼声