Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

Is there a well-liked solution for handing nested model forms?

Gems / Libraries • Asked by Rutul Dave

I am not sure what the consensus is on the best approach to handling nested model forms is.
The solution in can work, but doesn't seem like it can scale.

Chris mentioned cocoon -

And in the comments, Daniel Kehoe seems to suggest using ActiveForm.

How do folks generally do nested forms?

I'm a fan of cocoon and have used it in many applications. If ActiveForm really does look like it might join Rails core, I'd be really curious about how well it works. Safe answer: cocoon. Adventurous answer: ActiveForm. :)

Thanks Chris. I tried out cocoon and it was a pretty straightforward to use. I guess I will go with the safe answer on this project :-).

I got cocoon working as well as I want.
Next though, I want to use the capabilities of cocoon and customize a bit.

For example, instead of having a 'Add another' link under the nested model, I want to to add the input field for the nested model when the user presses the enter key after adding a record for the nested model. So I want to trigger link_to_add_association when 'enter' key is pressed.

Any suggestions on how best to do that?

A solution that works, but feels/looks "hacky" is hiding the "add another" link and then trigger the click to that link when the enter key is pressed.

$("#nestedModelAttribute").keyup(function (e) {
if (e.keyCode == 13) {

I'd say that's probably a decent solution. What happens if the user doesn't know to press Enter and wants to create another model?

Thanks. It will be useful to have a + Add link as well.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.