Rails 4 nested form - no implicit conversion of Symbol into Integer

笑着哭i 提交于 2019-12-10 18:51:24

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17037803/rails-4-nested-form-no-implicit-conversion-of-symbol-into-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!