Reputation: 34643
In my rails 4 app, I have a triple nested route:
devise_for :users do
resources :foo do
resources :marflar
end
end
And I have a form for creating a new Foo with an embedded Marflar object:
<%= form_for(@foo) do |f| %>
<%= f.text_field :foo_attr %>
<%= f.fields_for :marflars_attributes do |marflars_form| %>
<%= marflars_form.text_field :marflar_attr %>
<% end %>
<%= f.submit %>
<% end %>
But when I submit the form I get:
TypeError in FoosController#create
no implicit conversion of Symbol into Integer
The relevant parts of my Foo Controller look like this:
def new
@foo = current_user.foos.build
@foo.marflars.build
end
def create
@foo = Foo.new(foo_params)
if @foo.save
redirect_to @foo
else
render action: 'new'
end
end
..
def foo_params
params.require(:foo).permit(:foo_attr, marflars_attributes: [:marflar_attr])
end
And my models are as you'd expect:
class Foo < ActiveRecord::Base
belongs_to :user
has_many :marflars, dependent: :destroy
accepts_nested_attributes_for :marflars, allow_destroy: true
end
class Marflar < ActiveRecord::Base
belongs_to :foo
end
Why won't this work? It's driving me nuts. I'm thinking of switching to form objects, but I'd like to get this working first.
Upvotes: 3
Views: 6006
Reputation: 84182
Your fields_for
call should be just
<%= f.fields_for :marflars do |marflars_form| %>
<%= marflars_form.text_field :marflar_attr %>
<% end %>
Rails takes care of the parameter naming conventions expected by nested attributes.
Upvotes: 6