我搜索了很长时间,但找不到解决方案。这是我的模特:
web.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
user.rb
class User < ActiveRecord::Base
has_one :web, :as => :role
attr_accessible :dob, :fname, :lname
end
org.rb
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"}
请帮助。
答案 0 :(得分:1)
在Web
中,添加:
attr_accessible :role_attributes
accepts_nested_attributes_for :role
编辑:最初将其设为User
,但设计资源为Web
。
Edit2:错过了as: :role
。更改了attr值以反映。