Sometimes you would like to create one form for a model and some of its associations. This has always been a bit tedious because you had to re-roll a solution everytime. Last year a start on a unified solution was made with the association macro :accessible option. However, because it only supported nesting of models during creation it was pulled out before the 2.2 release.
However, since this is a rather large patch I will give you a quick tour on what it does and how to use it so you can start reporting issues or give feedback in general. We are especially interested in feedback from people that allow deletion of records through their forms, and how the provided solutions work for them.
Getting the patches
Lets start by creating a new application:
And vendor my Rails branch with the nested models patches:
From here on the user is expected to know where to put which code.
Consider a form which would allow the user to simultaneously create (or edit) a project and its tasks:
Before my patch
Previously this meant you would have to write template code like the following:
The controller is pretty much the same as your average restful controller. The Project model, however, needs to know how to handle the nested attributes:>
After my patch
First tell the Project model to accept nested attributes for its tasks:
Then lets look at the template code:
As you can see this is more readable and concise. Granted, in this example it’s not much compacter, but imagine what the example would have looked like if the project had more nested models. Or if the Task model even had nested models of its own…
With this patch it should be possible to create nested model forms as deep as you would want to. Creating, saving, and deleting should all work transparently and inside one transaction.