1

私にはユーザーがいます。これは、管理者、学生、教師の3つのタイプのいずれかになります。誰もが他の属性を持っています。私はこのように1対1でポリモーフィックな関連付けを試みています:

ユーザー

class User < ActiveRecord::Base
    belongs_to :identity, :polymorphic => true
    accepts_nested_attributes_for :identity, :allow_destroy => true

    attr_accessible :email, :login, :remember_token, 
                    :password_confirmation, :password, :role
end

学生

class Student < ActiveRecord::Base
    attr_accessible :field

    has_one :user, :as => :identity
end

コントローラ

def new
     @user = User.new
end
def create
    @user = User.new(params[:user]) # It fails here.
    @user.identita.build
    ...
end

意見

<%= form_for(@user) do |f| %>
    <%= f.label :login %><br />
    <%= f.text_field :login %>

    <%= f.fields_for [:identity, Student.new] do |i| %>  
    <%= i.label :field %><br />
    <%= i.textfield_select :field  %>
    <% end %>
<% end %>

このビューを送信すると(より複雑ですが、これがコアです)、次のようなハッシュが送信されます。

{"utf8"=>"✓",
 "authenticity_token"=>"...",
 "user"=>{"login"=>"...",
 "student"=> {"field"=>"..."}
}

したがって、コントローラーのマークされた行で次のように失敗します。

ActiveModel::MassAssignmentSecurity::Error in UsersController#create
Can't mass-assign protected attributes: student

私は何が間違っているのですか?:as => "student"のようなもの、または実現をねじる?

4

2 に答える 2

4

まず、修正します。

<%= f.fields_for [:identity, Student.new] do |i| %>  

に:

<%= f.fields_for :identity, Student.new do |i| %>

第二に、あなたは関係で使用しようとしていaccepts_nested_attributes_forますbelongs_to。これはサポートされていない動作AFAIKです。おそらくそれをStudentモデルに移動してみてください:

class Student < ActiveRecord::Base
  attr_accessible :field

  has_one :user, :as => :identity
  accepts_nested_attributes_for :user, :allow_destroy => true
end

次のようなビューを作成します。

<%= form_for(Student.new) do |i| %>
  <%= i.fields_for :user, @user do |f| %>  
    <%= f.label :login %><br />
    <%= f.text_field :login %>
  <% end %>
  <%= i.label :field %><br />
  <%= i.textfield_select :field  %>
<% end %>
于 2012-08-09T20:19:50.127 に答える
0

attr_accessibleのドキュメントから

attr_accessibleは、このリストの属性のみを設定し、ダイレクトライターメソッドを使用できる残りの属性に割り当てます。

したがって、を使用attr_accessibleすると、別の属性が自動的に保護された属性になります。

于 2012-08-09T20:15:11.890 に答える