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 %> 
+0

您可以添加您的视图文件的代码?而应该是':illustrated_attributes'。 – 2013-02-09 21:46:00

+0

另一件事是在员工#新操作中用'@ employee.build_picture'替换这一行'@employee.picture = Picture.new'。这是用has_one/belongs_to关联建立关联记录的正确方法。 – 2013-02-09 22:01:11

+0

谢谢 - 添加了视图代码。我在模型中尝试了':illustrated_attributes',但得到了同样的错误。也更改为'@ employee.build_picture',但仍然收到相同的错误。 – 2013-02-09 22:02:40

回答

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| %>