ruby-on-railswebpackercocoon-gem

Rails cocoon nested form: webpacker can't find cocoon


I'm using the cocoon gem to build nested forms as I would like the user to fill in as many 'sub_step' as he wants in a 'main_step' form.

Here is my code:

MainStep model

class MainStep < ApplicationRecord
    belongs_to :user
    has_many :sub_steps, inverse_of: :main_step
    accepts_nested_attributes_for :sub_steps, reject_if: :all_blank, allow_destroy: true
end

SubStep model

class SubStep < ApplicationRecord
    belongs_to :main_step
end

sub_steps_controller

def index
    @sub_step = SubStep.new
    @main_step = current_user.main_step.last
end

def create
    # runs after I submit the form
end

sub_steps/index.html.erb

<%= form_for @main_step do |f| %>
     <%= f.fields_for @sub_step do |step| %>
         <%= render 'sub_step_fields', :f => step %>
     <% end %>
     <%= link_to_add_association 'Add', f, :sub_steps %>
     <% f.submit 'Confirm' %>
<% end %>

sub_steps/_sub_step_fields.html.erb

<div class='nested-fields'>
    <div class="field">
        <%= f.label :created_at %>
        <%= f.text_field :created_at %>
    </div>
    <%= link_to_remove_association "Remove", f %>
</div>

When I'm loading the page where the form is, nothing happens when I click on the 'Add' button. By inspecting the logs, I noticed that webpacker can't find the cocoon gem, so the form is not working as it's supposed to.

I'm using Rails 6.0.2, thanks.


Solution

  • After more research, I ended up here: https://github.com/nathanvda/cocoon/pull/454

    What worked for me is the following:

    yarn add cocoon-js

    and then add to my application.js

    import 'cocoon-js';