Cocoon add association, how to limit number of associations

前端 未结 2 1421
渐次进展
渐次进展 2020-12-17 02:36

I am creating a system that stores cards using Ruby/Rails/HAML - In this case there is a Card class that has many Colours (this is also a class). When creating and editing a

2条回答
  •  [愿得一人]
    2020-12-17 02:52

    I would use javascript for this. You can bind to an event that is triggered upon insert of a new item: on this event count how many items there are, and hide the link if needed.

    Likewise, when loading the page do the same.

    So in code that would look like:

     $(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();     
     });
    

    Something like this should work. Note this code is not tested :)

    Hope this helps.

提交回复
热议问题