为 coccon 添加限制 gem

Add limit to coccon gem

我有一个 secondaryparents table 我想将添加按钮限制为只有 1 个 secondaryparents。

<div id ='secondaryparents'>
  <%= f.fields_for :secondaryparents do |builder| %>
  <%= render 'secondaryparent_fields', :f => builder %>
  <% end %>
  <%= link_to_add_association 'Add Secondary Parent', f, :secondaryparents, limit: 1 %>
</div>

我尝试添加 limit: 1 但它不起作用。有什么办法可以实现吗?

您可以使用 JS 事件取消操作

https://github.com/nathanvda/cocoon#canceling-a-callback

类似的东西:

$('#secondaryparents').on('cocoon:before-insert', function(event, insertedItem) {
  if($('css seletor').length > 1){
    event.preventDefault();
  }
});

我的首选方法是隐藏 link 以在达到请求的数量时添加新项目。

一个简单的方法是使用 cocoon:after-insertcocoon:after-remove 回调,计算触发时插入的项目数和 hide/show link_to_add_association link 在需要的时候。

Note: since this is imho a UX choice, it is not implemented as such in cocoon as a feature. I believe it is a best practice to not show clickable things which we know beforehand are not going to give any results. But opinions and practices differ :)

示例实现:https://github.com/nathanvda/cocoon/wiki/How-to-limit-the-number-of-nested-fields

<script type="text/javascript">
  $(function() {
    // console.log('dfdsfdsf')
  // limits the number of categories
  $('#secondaryparents').on('cocoon:after-insert', function() {
    $('#add-category a').hide();
  });

  $('#secondaryparents').on('cocoon:after-remove', function() {
    $('#add-category a').show();
  });

    if (<%= @parent.secondaryparents.length %>) {
    $('#add-category a').hide();
  }

})
</script>