With the following code and result below, why does the cars_attributes
index (i.e. name=owner[cars_attributes][>>>0<<<][color]) increment in
the second fields_for block when only one car is built? Shouldn’t it
stay the same because only one car was built?
Is this standard behavior? If so, what is the standard way to force
both indexes to be 0 (or increment together if there are more
records)?
This is an over-simplified example. The reason I want two fields_for
blocks is due the arrangement of partials in another complex form.
Much thanks!
Matt
owners_controller.rb
…
def new
@owner = Owner.new
@owner.cars.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @owner }
end
end
…
owner.rb
class Owner < ActiveRecord::Base
has_many :cars
accepts_nested_attributes_for :cars
end
car.rb
class Car < ActiveRecord::Base
belongs_to :owner
end
new.html.erb
<%= form_for(@owner) do |f| %>
<% if @owner.errors.any? %>
<%= pluralize(@owner.errors.count, “error”) %> prohibited
this owner from being saved:
<ul>
<% @owner.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :name %>
Cars
<%= f.fields_for :cars do |car_fields| %>
<%= car_fields.label :color %>
<%= car_fields.text_field :color %>
<% end %>
=======
<%= f.fields_for :cars do |car_fields| %>
<%= car_fields.label :plate %>
<%= car_fields.text_field :plate %>
<% end %>
http://localhost:8081/owners/new
…
Cars
<div class="field">
<label for="owner_cars_attributes_0_color">Color</label><br />
<input id="owner_cars_attributes_0_color"
name=“owner[cars_attributes][0][color]” size=“30” type=“text” />
=======
<div class="field">
<label for="owner_cars_attributes_1_plate">Plate</label><br />
<input id="owner_cars_attributes_1_plate"
name=“owner[cars_attributes][1][plate]” size=“30” type=“text” />