ネストされた属性の一括割り当てに関連する問題をたくさん調べましたが、どれも役に立ちませんでした...
私はDeviseを使用しており、次User
のような異なるタイプのモデルを1つ持っています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