How to use cocoon gem in Rails 6
Asked Answered
Y

4

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?

Yaker answered 17/9, 2019 at 13:3 Comment(0)
Y
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";

Yaker answered 18/9, 2019 at 5:3 Comment(3)
Not working. Getting error like "undefined method `link_to_add_association' for"Hanafee
@faisalbhatti you'll have to install gem too as we do normally. this is for just the part where we import javascript fileYaker
Actually we should call on appplication.js " import 'cocoon/app/assets/javascripts/cocoon' "Mcchesney
T
3

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

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

Tori answered 17/9, 2019 at 14:48 Comment(0)
E
2

First: run

yarn add cocoon-js

Second: add to application.js

import 'cocoon-js'
Elbertine answered 4/4, 2020 at 19:30 Comment(1)
What about the link_to_add_association and other helper methods?Landlordism
C
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

Contraption answered 23/3, 2021 at 0:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.