Rails 6, Webpacker, and the Cocoon gem

A straightforward way to use the Cocoon gem in your Rails 6 project, using Webpacker.

Posted by Curtis Miller Curtis Miller

If you're not familiar with the Cocoon gem, it's an awesome little gem to help with easily handling nested forms. We've used it with great success on many of our Rails projects.

The docs currently say that it supports Rails 3, 4, and 5, but there's no mention of Rails 6, or Webpacker. Having started a new Rails 6 project recently, this was unfortunate. Luckily, it was pretty easy to get Cocoon installed and working.

Buried in an open issue is some information on how to get set up. Here's what we did:

  1. You will need the gem, so add
    gem 'cocoon'
    to your Gemfile, then bundle as normal.
  2. You will also need the JavaScript package, so from the root of your Rails app, run
    yarn add github:nathanvda/cocoon#c24ba53
    If you check your package.json you should see Cocoon is now listed.
  3. Then, add Cocoon to your list of requires in the app/javascript/packs/application.js file, like so:
    require("cocoon")

One last note, Cocoon currently requires jQuery, so be sure that's installed as well. If you need help with that, check out how to install jQuery using Webpacker in Rails 6. You should be all set to handle nested forms in your Rails app now. If I missed anything, let me know in the comments!



Velocity Labs

Need web application development, maintenance for your existing app, or a third party code review?

Velocity Labs can help.

Hire us!