The reason I really really dig the Rails fields_for helper is this reason:
<%= fields_for "parent[child_object_name][]", child_object_instance do |f| %>
<%= f.text_field :attribute%>
<%end%>
Generates ...
<input id="parent_child_object_name_#{child_object_instance.id}"
name="parent[child_object_name[#{child_object_instance.id}]]" />
In fact you could even try ...
<%= fields_for "parent[child_object_name][]", child_object_instance do |f| %>
<%= f.text_field :attribute, :index=>child_object_instance.name%>
<%end%>
<input id="parent_child_object_name_#{child_object_instance.name}"
name="parent[child_object_name[#{child_object_instance.name}]]" />
This really helps when you're trying to pump in or edit a complicated object graph through a form that was originally designed for a single model. I love this approach because it saves me the trouble of having to initialize my objects in my controller actions in accordance to the way the form was designed just so Rails can populate the fields with the right values.
There's also a cool RailsCast about using fields_for in comlex forms.
1 Response to Rails fields_for is the cheese
Could you update this post for Rails 2.0 - I've been having a hell of a time getting this to work for 2.0.
Something to say?