不会将Symbol隐式转换为Integer

不会将Symbol隐式转换为Integer

本文介绍了Rails 4嵌套形式-不会将Symbol隐式转换为Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails 4应用程序中,我有一条三层嵌套路线:

In my rails 4 app, I have a triple nested route:

devise_for :users do
  resources :foo do
    resources :marflar
  end
end

我有一个用于使用嵌入式Marflar对象创建新Foo的表单:

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

我的Foo Controller的相关部分如下所示:

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.

推荐答案

您的fields_for调用应该是

<%= f.fields_for :marflars do |marflars_form| %>
  <%= marflars_form.text_field :marflar_attr %>
<% end %>

Rails处理嵌套属性期望的参数命名约定.

Rails takes care of the parameter naming conventions expected by nested attributes.

这篇关于Rails 4嵌套形式-不会将Symbol隐式转换为Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 23:25