1
我在为has_one多态模型提交嵌套形式时遇到质量分配错误。表单正在尝试创建基于polymorphic association Rails guide的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
...
错误
在模型中,我试过的每个排列:图文并茂,:图片,: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 %>
您可以添加您的视图文件的代码?而应该是':illustrated_attributes'。 – 2013-02-09 21:46:00
另一件事是在员工#新操作中用'@ employee.build_picture'替换这一行'@employee.picture = Picture.new'。这是用has_one/belongs_to关联建立关联记录的正确方法。 – 2013-02-09 22:01:11
谢谢 - 添加了视图代码。我在模型中尝试了':illustrated_attributes',但得到了同样的错误。也更改为'@ employee.build_picture',但仍然收到相同的错误。 – 2013-02-09 22:02:40