3

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.

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189

1 Answers1

6

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.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • Many thanks, this resolves the error I was getting. I now get a stack level too deep error, but I'll open a new question for that that if I can't fix it myself. Cheers. – stephenmurdoch Jun 11 '13 at 08:16