为 has_one 多态模型提交嵌套表单时出现批量分配错误。该表单试图基于多态关联 Rails 指南创建 Employee 和 Picture 实例。
对于 has_one 多态模型的嵌套创建表单的任何功能示例,我将不胜感激!我知道有大量关于批量分配错误的问题,但我从未见过多态关联的工作示例。
楷模
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"}
在模型中,我尝试了 :illustrated、:picture、:illustrated_attribute、:illustrated_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 %>