ruby-on-rails - 使用嵌套表单时无法批量分配 protected 属性设计错误

标签 ruby-on-rails devise simple-form

我已经搜索了很长时间,但找不到解决方案。这是我的模型:

网站.rb

class Web < ActiveRecord::Base
   devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :user_type, :remember_me

  belongs_to :role, :polymorphic => true
end

用户名
class User < ActiveRecord::Base
 has_one :web, :as => :role
 attr_accessible :dob, :fname, :lname
end

组织文件
class Org < ActiveRecord::Base
  has_one :web, :as => :role
  attr_accessible :name, :website
end

一切似乎都很好,直到我在 devise/registration/new.html.erb 中使用 simple_form_for 而不是普通的 form_for
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :class => 'form-horizontal' }) do |f| %>

  <%= f.input :email, label: false, :input_html => { :class => "span6", placeholder: "Email", type: "email", required: true}%>

  <%= f.input :password, label: false, :input_html => { :class => "span6", placeholder: "Password", type: "password" }%>

  <%= f.input :password_confirmation, label: false, :input_html => { :class => "span6", placeholder: "Re-enter Password", type: "password" }%>

  <%= f.input :user_type, as: :hidden, :input_html => { :value => user_type} %>

  <%= f.simple_fields_for resource.role do |rf| %>
    <%= render :partial => "#{child_class_name.underscore}_fields", :locals => { :f => rf } %>
  <% end %>
  <%= f.submit "Sign up" %>
<% end %>

嵌套部分使用包含相应字段的适当 model_fields 名称放置部分。

*_org_fields.html.erb*
<%= f.text_field :name, :class=>"span6", :type=>"text", :placeholder=>"Name", :required=>"" %><br />
<%= f.text_field :website, :class=>"span6", :type=>"text", :placeholder=>"Website", :required=>"" %>

问题在于 f.simple_fields_for,如果我删除 simple_ 一切正常。但我不希望它被删除。我遇到的错误是:
 ActiveModel::MassAssignmentSecurity::Error in Devise::RegistrationsController#create

 Can't mass-assign protected attributes: org

请求参数为:
{"utf8"=>"✓",
 "authenticity_token"=>"NnsyNdrrKJmd8QutqVs6HqZi0EnQmAmZF7zGYqnu+rI=",
 "web"=>{"email"=>"",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "user_type"=>"org",
 "org"=>{"name"=>"",
 "website"=>""}},
 "commit"=>"Sign up"}

请帮忙。

最佳答案

Web , 添加:

attr_accessible :role_attributes
accepts_nested_attributes_for :role

编辑:最初将其设为 User但设计资源是 Web .

Edit2: 错过了 as: :role .更改了 attr 值以反射(reflect)。

关于ruby-on-rails - 使用嵌套表单时无法批量分配 protected 属性设计错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17901096/

相关文章:

ruby-on-rails - 如何删除重复的验证错误

javascript - 来自另一个 Controller 的 Rails : Render a . js.erb?

ruby-on-rails - 使用 Couchbase 设计 Rails

ruby-on-rails - 设计不填写resource.errors 登录

ruby-on-rails - Rails 4 simple_form collection_select

css - Simple_form 颜色样式

ruby-on-rails - 如果参数为空,如何从数据库 Rails 设置默认值

ruby-on-rails - Rails 将变量添加到另一个变量

除非刷新,否则 JavaScript 不会加载

ruby-on-rails - Rails 6 中的另一个 ActionController::InvalidAuthenticityToken