【问题标题】:Can't mass-assign protected attributes in has_one association in Rails 3.2无法在 Rails 3.2 的 has_one 关联中批量分配受保护的属性
【发布时间】:2016-01-21 23:48:41
【问题描述】:

我在这里查看了许多帖子并应用了许多答案,但均未成功。所以在这里...保持简单...包括使用 simple_form。

在我的用户模型中,我有:

has_one :instrument
accepts_nested_attributes_for :instrument
attr_accessible ... :instrument_attributes

在我的仪器模型中,我有:

belongs_to :user
attr_accessible :user_id, :do_inst1, :do_inst2, :do_inst3, :do_inst4

在我的用户控制器中,我有:

def new
  @user = User.new
  @user.build_instrument
end

def create_user
  @user = User.new(params[:user]) # <== THE LINE PRODUCING THE ERROR

  respond_to do |format|
    if @user.save
      format.html {redirect_to users_path, notice: "User created successfully."}
    else
      format.html { render action: "new" }
    end
  end
end

在我的新用户 _form.html.erb 中,我有:

<%= simple_nested_form_for :user, url: create_user_users_path do |f| %>
    <%= f.input :first_name %>
    <%= f.input :last_name %>

    <%= f.fields_for :instrument do |instrument_f| %>
        <%= instrument_f.check_box :do_inst1 %>
        <%= instrument_f.check_box :do_inst2 %>
        <%= instrument_f.check_box :do_inst3 %>
        <%= instrument_f.check_box :do_inst4 %>
    <% end %>

    <%= f.button :submit, "Register User" %>
<% end %>

错误信息: 无法批量分配受保护的属性:仪器 app/controllers/users_controller.rb:51:in `new' 第 51 行在上面用“#

【问题讨论】:

  • 你能发布@user.build_do_instrument的定义吗?
  • 您遇到问题的属性是什么?你能发布错误吗?
  • 为了减少混淆,我将“do_instrument”改为“instrument”,但只有一处。对不起。
  • 在帖子末尾添加了错误消息。谢谢。
  • f.fields_for :do_instrument 看起来不像写的。您应该通过模型名称引用该表单。

标签: ruby-on-rails ruby-on-rails-3.2


【解决方案1】:

你为什么要使用

<%= f.fields_for :do_instrument do |instrument_f| %>

而不是

<%= f.fields_for :instrument do |instrument_f| %>

您始终可以检查传入的参数以检测错误的来源。您可以在各自的控制器方法中编写此代码并查看终端以进行输出。

puts "*"*30
puts params
puts "*"*30

这是诊断问题的最简单方法,否则您可以使用不同的 gem 进行调试。

【讨论】:

  • 是的......你是对的。我试图通过将“do_instrument”更改为“instrument”来简化语法,但我错过了一些。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
相关资源
最近更新 更多