I am trying to use the Cocoon gem to add users to an asset. The only issue is that I need to have it set up to limit the amount of user associations that can be applied to an asset based on the type of asset they are (hardware/software, with hardware being 1, software won't be defined). At the moment I can just keep adding user associations to the asset. Is there any way to limit the amount of associations?
Any help is appreciated. Thank you in advance.
Asset.show:
- if @asset.users.empty?
= simple_form_for([@asset_profile, @asset]) do |f|
#assets_users
= f.simple_fields_for :assets_users do |assets_user|
= render "assets_user_fields", :f => assets_user
.links
= link_to_add_association "Add Another User", f, :assets_users
= f.submit
_assets_users_fields.html.haml:
.nested-fields
= f.input :user_id, collection: @users.order(:last_name), :label => "User"
= link_to_remove_association "Remove", f
I tried a solution I saw on another question, but I am getting an error stating Uncaught TypeError: number is not a function
at if $("#assets_users .nested-fields").length() is 1
.
The javascript I tried:
$ ->
check_to_hide_add_link = ->
if $("#assets_users .nested-fields").length() is 1
$("#assets_users .links a").hide()
else
$("#assets_users .links a").show()
return
$("#assets_users").bind "cocoon:after-insert", ->
check_to_hide_add_link()
return
$("#assets_users").bind "cocoon:after-remove", ->
check_to_hide_add_link()
return
check_to_hide_add_link()
return
Once again, any help is much appreciated.
EDIT: Link to referred question: Cocoon add association, how to limit number of associations
Generated javascript:
$(function() {
var check_to_hide_add_link;
check_to_hide_add_link = function() {
if ($("#assets_users .nested-fields").length() === 1) {
return $("#assets_users .links a").hide();
} else {
return $("#assets_users .links a").show();
}
};
$("#assets_users").bind("cocoon:after-insert", function() {
return check_to_hide_add_link();
});
$("#assets_users").bind("cocoon:after-remove", function() {
return check_to_hide_add_link();
});
return check_to_hide_add_link();
});
Getting rid of ()
on .length
ended up being the solution for the error message. Just a problem with my conversion of javascript to coffeescript.
Here's a link to the new question I opened up to further delve into my specific problem, in case anyone has the same: Javascript: Using a method from model in javascript code