Cocoon添加关联,如何限制关联数量

我正在创建一个使用Ruby / Rails / HAML存储卡的系统 – 在这种情况下,有一个Card类有很多颜色(这也是一个类)。 在创建和编辑卡片时,我正在使用Cocoon gem来动态添加颜色关联。

我遇到的问题是,在卡片模型中,卡片最多只能有5种颜色。 然而,界面允许添加无限的颜色,从而导致错误。

在Cocoon中是否有办法限制可以添加到表单的关联数量,以便不超过此限制?

这是添加/编辑卡片的表单代码

= simple_form_for @card, multipart: true do |c| = c.input :name, label: "Name of the card" = c.input :cost, label: "Cost of the card" #colours = c.simple_fields_for :colours do |colour| = render "colour_fields", f: colour .links = link_to_add_association 'add colour', c, :colours 

这是colour_fieldsforms

 .nested-fields = f.input :value, as: :select, collection: Colour::VALUES, selected: f.object.value, include_blank: false = link_to_remove_association "remove colour", f 

提前致谢。

我会用javascript来做这件事。 您可以绑定到插入新项目时触发的事件:在此事件上计算有多少项目,并在需要时隐藏链接。

同样,加载页面时也一样。

所以代码看起来像:

  $(function() { function check_to_hide_or_show_add_link() { if ($('#colours .nested-fields:visible').length == 5) { $('#colours .links a').hide(); } else { $('#colours .links a').show(); } } $('#colours').on('cocoon:after-insert', function() { check_to_hide_or_show_add_link(); }); $('#colours').on('cocoon:after-remove', function() { check_to_hide_or_show_add_link(); }); check_to_hide_or_show_add_link(); }); 

这样的事情应该有效。 注意这段代码没有经过测试:)

希望这可以帮助。

我有类似的任务要做,我最后做的是在“添加”链接上放置一个onclick事件。 此onclick事件将在执行添加字段的代码之前执行。

在您的情况下,代码将类似于以下内容:

 = link_to_add_association 'add colour', c, :colours, class: 'add-colour-link' 

然后在您的JavaScript(本例中的CoffeeScript)中:

 $('.add-colour-link').on 'click', (e) -> if $('#colours .nested-fields:visible').size() < 5 return true #continue the execution else #maybe display the modal to the user that only a maximum of 5 is allowed return false #prevent further execution