From 3b89aa605c543e772678e03add1818520c02bec8 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Sun, 15 Mar 2009 16:21:56 +0100 Subject: Added a collection association form example. --- railties/guides/source/nested_model_forms.textile | 47 ++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile index e975b97ea8..4b685b214e 100644 --- a/railties/guides/source/nested_model_forms.textile +++ b/railties/guides/source/nested_model_forms.textile @@ -174,4 +174,49 @@ When this form is posted the Rails parameter parser will construct a hash like t } -That’s it. The controller will simply pass this hash on to the model from the +create+ action. The model will then handle building the +address+ association for you and automatically be saved when the parent (+person+) is saved. \ No newline at end of file +That’s it. The controller will simply pass this hash on to the model from the +create+ action. The model will then handle building the +address+ association for you and automatically save it when the parent (+person+) is saved. + +h5. Nested form for a collection of associated objects + +The form code for an association collection is pretty similar to that of a single associated object: + + +<% form_for @person do |f| %> + <%= f.text_field :name %> + + <% f.fields_for :projects do |pf| %> + <%= f.text_field :name %> + <% end %> +<% end %> + + +Which generates: + + +
+ + + + +
+ + +As you can see it has generated 2 +project name+ inputs, one for each new +project+ that’s build in the controllers +new+ action. Only this time the +name+ attribute of the input contains a digit as an extra namespace. This will be parsed by the Rails parameter parser as: + + +{ + "person" => { + "name" => "Eloy Duran", + "projects_attributes" => { + "0" => { "name" => "Project 1" }, + "1" => { "name" => "Project 2" } + } + } +} + + +You can basically see the +projects_attributes+ hash as an array of attribute hashes. One for each model instance. + +NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep. + +TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example. \ No newline at end of file -- cgit v1.2.3