15

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?

Sikandar Tariq
  • 1,296
  • 1
  • 13
  • 29

4 Answers4

25

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";

Sikandar Tariq
  • 1,296
  • 1
  • 13
  • 29
3

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

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

Hackman
  • 1,614
  • 1
  • 12
  • 15
2

First: run

yarn add cocoon-js

Second: add to application.js

import 'cocoon-js'
shilovk
  • 11,718
  • 17
  • 75
  • 74
0

Install the cocoon rubygem as usual

yarn add cocoon-js-vanilla

// app/javascript/packs/application.js At the top of this file do:

import "cocoon-js-vanilla";

Inspired by: https://github.com/joerodrig/cocoon-js