Skip to main content

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 https://gorails.com/episodes/forum-nested-attributes-and-fields-for can work, but doesn't seem like it can scale.

Chris mentioned cocoon - https://github.com/nathanvda/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) {
$('.add-another').trigger("click");
}
});


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 27,623+ 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.