megahra
megahra

Reputation: 335

Cocoon (Ruby Gem) not working in production

I am currently developing an application with Ruby on Rails and am trying to implement nested attributes with the cocoon gem: With my current configurations it works on my local machine, but not in production on my server. I have ideas why it does not work, but not how to fix it.

First, here is my manifest that includes cocoon:

application.js    

...
//= require cocoon
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require chartkick
//= require_tree .

I see the problem here: Cocoon is before jquery and jquery_ujs, therefore I get the following error in the console of the developer tools:

Uncaught ReferenceError: jQuery is not defined at cocoon.self-6874ad698cefd21cc1119b773550f61b5c1a60396460f015222af59293affe80.js?body=1:131

Even though I have the error, locally the nested attributes still work. In production on the other hand, the button to add the association (link_to_add_association) does not work anymore (it is clickable, but does nothing, not even throwing an error). Of course I also tried to rearrange the manifest and put jquery and jquery_ujs before cocoon: But then cocoon does not work properly anymore: Instead of inserting one element with link_to_add_association, cocoon inserts two.

This is the head of my application.html:

application.html.erb

..
  <%= csrf_meta_tags %>
  <%= javascript_include_tag 'https://www.gstatic.com/charts/loader.js' %>
  <%= javascript_include_tag 'application', 'chartkick' %>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
..

Here are relevant parts of my Gemfile (ruby 2.3.1p112 is installed on the production server):

Gemfile

..
gem 'rails', '5.0.2'
gem 'jquery-rails', '4.2.2'

..
# Used for the dynamic forms:
gem 'simple_form', '3.4.0'
gem 'cocoon', '1.2.9'

..

I have no idea why cocoon inserts entries twice or why the application does not work in production. Does anyone have an idea how I can fix the problem?

Upvotes: 2

Views: 680

Answers (2)

nathanvda
nathanvda

Reputation: 50057

You include the application.js twice, this means that the cocoon javascript is also included twice, so there will be two click-handlers for cocoon:

<%= javascript_include_tag 'application', 'chartkick' %>
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

Imho you should just delete the first line.

Upvotes: 0

Simon Franzen
Simon Franzen

Reputation: 2727

only reference chartkick once

remove line <%= javascript_include_tag 'application', 'chartkick' %> from your layout

Upvotes: 0

Related Questions