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
I had a similar task to do and what I ended up doing was putting an onclick event on the "Add" link. This onclick event will execute before the code to add the fields is executed.
In your case, the code would look something like the following:
= link_to_add_association 'add colour', c, :colours, class: 'add-colour-link'
Then in your JavaScript (CoffeeScript in this case):
$('.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