rails - 多态关联 - 一对一 - 表单提交名称错误的嵌套字段

时间:2012-08-09 19:52:52

标签: ruby-on-rails polymorphic-associations

我有User,可以是以下三种类型之一:Admin,Student,Teacher。每个人都有其他属性。我像这样一对一地尝试多态关联:

用户

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 =&gt;“学生”或扭曲关系?

2 个答案:

答案 0 :(得分: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 %>

答案 1 :(得分:0)

来自documentation of attr_accessible

  

attr_accessible只会在此列表中设置属性,将分配给    其余属性您可以使用直接编写器方法。

因此,一旦您使用attr_accessible,其他属性将自动成为受保护的属性。