Search code examples
javascriptjqueryruby-on-rails-6cocoon-gem

# added to URL when clicking link_to_add OR link_to_remove_association


I'm using Rails 6 and I'm trying to make nested_fields work. I'm using Cocoon. There is no JS error, JQuery is correctly loaded. The nested_form loads the nested data correctly, but I'm unable to add a new line or remove an existing line. This is my code:

In _form.html.erb

<div id="entry_links">
     <%= f.fields_for :entry_links do |ff| %>
          <%= render 'entry_link_fields', f: ff %>
     <% end %>  
</div>    
<div id="links">
     <%= link_to_add_association '<span class="oi" data-glyph="plus" title="icon name" aria-hidden="true"></span> Add Link '.html_safe, f, :entry_links, class: "btn btn-primary" %>
</div>

_entry_link_fields.html.erb

<div class="nested-fields">
    <div class = "field row">
        <div class="col-md-1">
            <%= f.text_field :link_type, class: "form-control" %>
        </div>
        <div class="col-md-3">
            <%= f.text_field :label, class: "form-control" %>
        </div>
        <div class="col-md-6">
            <%= f.text_field :link, class: "form-control" %>
        </div>
        <div class="col-md-1">
            <%= f.number_field :line, class: "form-control" %>
        </div>
        <div class="col-md-1">
            <%= link_to_remove_association '<span class="oi" data-glyph="trash" title="icon name" aria-hidden="true"></span>'.html_safe, f, class: "btn btn-danger" %>
        </div>
     </div>
</div>

Just in case, here's a snippet of my package.json file which lists jQuery and coocon

{
     "cocoon-js": "^0.0.5",
     "jquery": "^3.5.1",
}

I've tried with both @nathanvda/cocoon AND cocoon-js-vanilla to no avail.

The only thing that happens when I click either of those links is that a "#" is added to the URL box. I read in another answer that it might be related to a JQuery error but that's not my case since my JS log doesn't show any error and I'm able to call other JQuery functions correctly from within the same app.


Solution

  • So it turns out that everything was correct, except I completely missed this line:

    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    

    After adding that line to my application.html.erb file, everything is correctly loaded and my links are working as expected.