In the set of new features from Rails 2.3, I was quite pleased by two of them: nested attributes and nested forms.
Both allow the creation of forms containing information about more than just one model, and may solve a recurrent problem I had in past projects, which has lead to some painful headaches…
Can’t wait to try it!
More information (source):
3.1. Nested Attributes
Active Record can now update the attributes on nested models directly, provided you tell it to do so:
class Book < ActiveRecord::Base has_one :author has_many :pages accepts_nested_attributes_for :author, :pages end
5.1. Nested Object Forms
Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using form_for and field_for. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model:
class Customer < ActiveRecord::Base has_many :orders accepts_nested_attributes_for :orders, :allow_destroy => true end
You can write this view in Rails 2.3:
<% form_for @customer do |customer_form| %> <div> <%= customer_form.label :name, 'Customer Name:' %> <%= customer_form.text_field :name %> </div> <!-- Here we call fields_for on the customer_form builder instance. The block is called for each member of the orders collection. --> <% customer_form.fields_for :orders do |order_form| %> <p> <div> <%= order_form.label :number, 'Order Number:' %> <%= order_form.text_field :number %> </div> <!-- The allow_destroy option in the model enables deletion of child records. --> <% unless order_form.object.new_record? %> <div> <%= order_form.label :_delete, 'Remove:' %> <%= order_form.check_box :_delete %> </div> <% end %> </p> <% end %> <% end %> <%= customer_form.submit %> <% end %>




