Josh Hepworth

Building Forms for Rails Associations with Cocoon

If you've ever built a Rails model that has a has_many relationship and needed to create a form for that relationship, you should check out the cocoon gem. It provides a no hassle, flexible way to build forms for anything you can add accepts_nested_attributes_for to.

The gem's README provides everything needed to get started, so it's a good place to begin.

If you're going to need more complex behavior in the way it adds additional forms for each nested object, check out the data-association-insertion-method option for link_to_add_association. It provides hooks you'll need to make sure the fields show up in the right place in your HTML.