1

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

controllers / 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 %>
4

1 に答える 1

0

ネストされた属性を適切に指定する必要があります。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| %>
于 2013-02-09T22:28:43.453 に答える