7

我正在创建一个使用 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_fields 表格

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

提前致谢。

4

2 回答 2

15

我会为此使用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();     
 });

像这样的东西应该工作。请注意,此代码未经测试:)

希望这可以帮助。

于 2012-10-25T17:23:01.490 回答
2

我有一个类似的任务要做,我最终做的是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
于 2014-09-26T19:30:26.120 回答