Typically when I use a fields_for
on a simple has_many
association, the input names on the form look something like foo[bars_attributes][0][name]
, but in my case, it's not showing up as an array on the form - instead I get something like foo[bars][name]
, which will blow up when I try to submit because it's trying to assign to a name property of an array - and I can't figure out what's different from other cases. Here's the code, which has obviously been simplified and renamed for this venue.
My model:
class Foo
has_many :bars
end
The controller:
class FooController < ApplicationController
def new
@foo = Foo.new
@foo.bars.build
@foo
end
end
The view:
<div>
<%= form_for @foo do |f| %>
<%= f.fields_for :bars do |bar_fields| %>
<%= bar_fields.text_field :name %>
<% end %>
<div class="single_column">
<%= f.submit "Submit" %>
</div>
<% end %>
</div>
The resulting markup:
<input name="foo[bars][name]" id="foo_bars_name" />
Perhaps Foo
could merit with having accepts_nested_attributes_for :bars
in it?