【问题标题】:Rails 4 nested form - no implicit conversion of Symbol into IntegerRails 4嵌套形式 - 没有将符号隐式转换为整数
【发布时间】:2013-06-11 06:29:58
【问题描述】:

在我的 rails 4 应用程序中,我有一个三重嵌套路由:

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

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

<%= 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 %>

但是当我提交表单时,我得到:

TypeError in FoosController#create
no implicit conversion of Symbol into Integer

我的 Foo 控制器的相关部分如下所示:

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

我的模型和你期望的一样:

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

为什么这不起作用?它快把我逼疯了。我正在考虑切换到表单对象,但我想先让它工作。

【问题讨论】:

    标签: ruby-on-rails nested-forms ruby-on-rails-4


    【解决方案1】:

    您的fields_for 电话应该只是

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

    Rails 负责嵌套属性所期望的参数命名约定。

    【讨论】:

    • 非常感谢,这解决了我遇到的错误。我现在得到一个堆栈级别太深的错误,但如果我自己无法修复它,我会为此提出一个新问题。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2017-01-19
    相关资源
    最近更新 更多