具有多态关联的质量分配错误

时间:2013-02-09 21:34:37

标签: ruby-on-rails model associations polymorphic-associations mass-assignment

在为has_one多态模型提交嵌套表单时,我收到了批量分配错误。表单正在尝试基于polymorphic association Rails guide创建Employee和Picture实例。

我非常感谢has_one多态模型的嵌套创建表单的 ANY 功能示例!我知道有大量关于质量分配错误的问题,但我从未见过有多态关联的实例。

模型

class Picture < ActiveRecord::Base
    belongs_to :illustrated, :polymorphic => true
    attr_accessible :filename, :illustrated
end

class Employee < ActiveRecord::Base
    has_one :picture, :as => :illustrated
    accepts_nested_attributes_for :picture
    attr_accessible :name, :illustrated_attribute
end

迁移

create_table :pictures do |t|
    t.string :filename
    t.references :illustrated, polymorphic: true
end

create_table :employees do |t|
    t.string :name
end

控制器/ employees_controller.rb

...
def new
    @employee = Employee.new
    @employee.picture = Picture.new
end

def create
    @employee = Employee.new(params[:employee])
    @employee.save
end
...

错误

Can't mass-assign protected attributes: illustrated

app/controllers/employees_controller.rb:44:in `create'

{"utf8"=>"✓", "authenticity_token"=>"blah"
 "employee"=>{"illustrated"=>{"filename"=>"johndoe.jpg"},
 "name"=>"John Doe"},
 "commit"=>"Create Employee"}

在模型中,我尝试了以下每种排列:图示,:图片,:illustrations_attribute,:illustrations_attributes,:picture_attribute,:picture_attributes等。任何提示或示例?

编辑:

_form.html.erb

<%= form_for(@employee) do |f| %>

  <%= f.fields_for :illustrated do |form| %>
    <%= form.text_field :filename %>
  <% end %>

    <%= f.text_field :name %>
    <%= f.submit %>

<% end %>

1 个答案:

答案 0 :(得分:0)

您需要适当地指定nested_attributes。 accepts_nested_attributes_for将关联名称作为参数,然后您需要将相同的assoc_attributes添加到attr_accessible。因此,将您的员工模型更改为

class Employee < ActiveRecord::Base
  has_one :picture, :as => :illustrated
  accepts_nested_attributes_for :picture
  attr_accessible :name, :picture_attribute
end

并将视图代码中的field_for行更改为

<%= f.fields_for :picture do |form| %>