Chris L.
Chris L.

Reputation: 39

Cocoon link_to_add/remove_association events not firing

I'm working on a Rails app which has a Badge model with many BadgeElements. I'm trying to allow dynamic adding and deleting of BadgeElements, and as I was having issues with ryanb's nested_form gem, I'm now looking at Cocoon. I believe I've installed the gem properly, but the events aren't firing. When I click on the links for adding or removing an association, the URL at the top of the page gets a # appended to it, but otherwise nothing happens. Here's the relevant code:

badge.rb:

class Badge < ActiveRecord::Base
  has_one :background, :dependent => :destroy
  has_many :badge_elements, :dependent => :destroy
  accepts_nested_attributes_for :background
  accepts_nested_attributes_for :badge_elements, :allow_destroy => true
  validates :title, presence: true, length:{minimum: 3}
end

_form.html.haml:

= form_for @badge, html:{class:"form-horizontal edit_badge", data:{id:@badge.id}} do |f|
  %table
    %tbody
      .field
        %tr
          %td= f.label :title
          %td= f.text_field :title
      #badge_elements
        = f.fields_for :badge_elements do |badge_element|
          = render 'badge_element_fields', :f => badge_element
        .links
          = link_to_add_association 'Add an element', f, :badge_elements

_badge_element_fields.html.haml:

.nested-fields
  .field
    %tr
      %td
      %td= f.label :side
      %td= f.text_field :side, id: "badge_element_#{f.object.id}_side"
    ...
    ...
   = link_to_remove_association "remove element", f

Upvotes: 1

Views: 1037

Answers (1)

nathanvda
nathanvda

Reputation: 50057

It seems you do not have the required javascript code. This could be due to a number of reasons (probably not exhaustive --a bit of guessing here) :

  • you did not add the //= require cocoon line to application.js
  • you did not include application.js in your application layout
  • you are not using jquery (or did not include it correctly)
  • you have any other error in your javascript code, which stops the javascript from processing. You should see an error in the javascript console of your browser.

Upvotes: 1

Related Questions