Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Rutul Dave asked in Gems / Libraries

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?

Reply

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. :)

Reply

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 :-).

Reply

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?

Reply

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");
}
});

Reply

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?

Reply

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

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,140+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.