我查看了很多与嵌套属性中的质量分配相关的问题,但没有一个能帮助我......
我正在使用 Devise 并有一个User
具有不同类型的模型,例如Client
:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation, :remember_me, :rolable_type
belongs_to :rolable, :polymorphic => true
accepts_nested_attributes_for :rolable
end
class Client < ActiveRecord::Base
has_one :user, :as => :rolable
attr_accessible :specialty, :address
end
我有以下表格用于创建具有客户端类型和客户端属性的新用户,并且正在工作:
[...]
resource.rolable = child_class_name.constantize.new if resource.rolable.nil?
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
[...]
<% # customized code begin %>
<%= fields_for resource.rolable do |rf| %>
<% if rolable_type == 'client' %>
<div><%= rf.label :specialty %><br />
<%= rf.text_field :specialty %></div>
[...]
<% end %>
<% end %>
<%= hidden_field :user, :rolable_type, :value => rolable_type %>
<% # customized code end %>
[...]
<div><%= f.submit "Sign up" %></div>
<% end %>
我有以下用于编辑同一用户但不起作用:我收到以下错误ActiveModel::MassAssignmentSecurity::Error in UsersController#update
::Can't mass-assign protected attributes: client
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
[...]
<% f.fields_for(@user.rolable) do |rf| -%>
<div><%= rf.label :specialty %><br />
<%= rf.text_field :specialty %></div>
<div><%= rf.label :address %><br />
<%= rf.text_field :address %></div>
<% end %>
[...]
这是我的UsersController
更新操作:
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
render 'edit'
end
end