如何在表单中只有一个 row/item 时隐藏删除 link using link_to_remove_association in rails

how to hide remove link when there is only one row/item in the form using link_to_remove_association in rails

我正在使用 cocoon gem 从 rails 中的表单 add/remove 记录 'on the fly'。如果只有一个row/item,有没有办法隐藏使用link_to_remove_association添加到页面上的删除link?

我会把它包装在一个 if 块中,例如

<% if foos.size > 0 %>
  <% link_to "Remove", remove_foo_path(foo) %>
<% end %>

我修好了。由于行是从 JS 添加的,控制删除 link 的 hiding/showing 必须从 JS 本身处理,而不是 rails.

$(document).ready(function() {
    $('#container')
      .on('cocoon:after-insert', function() {
        if($(".fields-row").length > 1){
          $(".remove_fields")[0].style.display="block";
        }else{
          $(".remove_fields")[0].style.display="none";
        }
      })
      .on("cocoon:after-remove", function() {
        if($(".fields-row").length == 1){
          $(".remove_fields")[0].style.display="none";
        }else{
          $(".remove_fields")[0].style.display="block";
        }
      });
});

.remove_fields class 在使用 link_to_remove_association

时自动添加到 <a> 标签

由于某些原因 JQuery 的 .show()/.hide() 方法不起作用,这就是我使用 .style.display

的原因

可以使用 FormBuilder 索引。

HAML:

.nested_fields
  %h3 Nested object
  - unless f.index == 0
    = link_to_remove_association "remove", f