Cocoon gem issue in Rails 7

2.3k Views Asked by At

I want to implement nested form using cocoon gem.

There is no error but when I click on the item link to edit and trigger it, nothing works. However, the URL chnages from http://127.0.0.1:3000/portfolios/2/edit to http://127.0.0.1:3000/portfolios/2/edit#.

I expect the input tag to show, but it does not.

View

_form.html.erb

<div class="form-group mb-3">
    <h2>Technologies used: </h2>
    <div>
      <%= form.fields_for :technologies do |technology_form|%>
       <%= render 'technology_fields', f: technology_form %>
      <% end %>
      <div>
        <%= link_to_add_association 'Add Technology', form, :technologies %>
      </div>
    </div>
</div>

_technolog_fields.html.erb

<div class="form-group mb-1 nested-fields">
  <%= f.label :name %>
  <%= f.text_field :name, class: 'form-control' %>
</div>

Model

portfolio model

class Portfolio < ApplicationRecord
  has_many :technologies
  accepts_nested_attributes_for :technologies,
                                reject_if: ->(attrs) { attrs['name'].blank? }
                                
end                                

I add cocoon gem to Gemfile and run bundle install

Alse, I add //= require cocoon to application.js

When I click on add technology, nothing happens.

I will appreciate your help.

Thanks.

2

There are 2 best solutions below

0
efatsi On

Are you using importmap with Rails 7? If so, then you'll need to change the way you include the JS.

First in your terminal you would:

./bin/importmap pin @nathanvda/cocoon

Then, somewhere in your JS you would:

import "@nathanvda/cocoon"

PS - you'll also need to pull in jQuery, either through a gem or perhaps again using importmaps.

0
hùng lê On

First, you need to install js dependencies

yarn add @nathanvda/cocoon 

Then, import it into javascript/application.js

import "@nathanvda/cocoon";

Otherwise, cocoon gem needs jquery to work well.
If you using StimulusJs (default js library in Rails 7), you can try this gem rondo_form. It same as Cocoon, but using Stimulus, not need jQuery.