Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use cocoon gem in Rails 6

Have been using cocoon gem for nested forms in rails 4 & rails 5 apps. Currently, I was updating one of the rails 5.2 app (which is using cocoon gem) to rails 6.

As rails 6 is using webpacker, so I tired to require cocoon javascript in application.js file as we used to do in previous versions of rails.

app/javascript/application.js

//= require cocoon

But unfortunately, things do not seem to work. Have also tried to import but of course, it's also not working as the cocoon is not available as a javascript package.

Any solution or alternate for this?

like image 318
Sikandar Tariq Avatar asked Sep 17 '19 13:09

Sikandar Tariq


2 Answers

Updated Solution: Cocoon package has been release so one can easily use this with wepacker

Inside your Gemfile add the following:

gem "cocoon"

Add the componanion package

yarn add @nathanvda/cocoon 

and then in your app/javascripts/packs/application.js you should add

require("jquery")
require("@nathanvda/cocoon")

Old Solution:

There is this Pull Request on cocoon GitHub repository that worked perfectly for me.

Package.json is provided in this branch so we can use yarn or npm to install package by providing GitHub repo link.

yarn add github:nathanvda/cocoon#c24ba53

Cocoon package will install and you can check your package.json file.

"cocoon": "github:nathanvda/cocoon#c24ba53"

commit number #c24ba53 is important, make sure it is included in your package.json file

After this, you can import cocoon.js in application.js file.

import "cocoon";

like image 148
Sikandar Tariq Avatar answered Nov 17 '22 01:11

Sikandar Tariq


There is an 'hack' on the cocoon page for this:

https://github.com/nathanvda/cocoon/issues/555

like image 3
Hackman Avatar answered Nov 17 '22 01:11

Hackman