Friday, September 7, 2012

Rails 3 - Model's nested attributes in form

When a rails form contain a model and its nested attributes, use "accepts_nested_attributes_for" to get parameter from the form.

e.g.

In a car model,
...
has_one :engine_spec
accepts_nested_attributes_for :engine_spec, allow_destroy => true
...


In a car form,
...
<%= form_for(@car, :multipart => true) do |f| %>
   <%= f.text_field :model_name %>
...
   <%= f.fields_for :engine_spec do |spec| %>
        <%= spec.text_field :capacity %>
...


Note:  Should declare engine_spec in car controller:
@car.engine_spec = EngineSpec.new

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.