accept_nested_attributes_for でこれらのモデルを使用して、「保存」と「作成」が異なる理由を理解するのに苦労しています。これは私のモデルです:
class Book < ActiveRecord::Base
has_many :pages
has_many :picture_pages, :through => :pages, :source => :pagetype, :source_type => 'PicturePage'
accepts_nested_attributes_for :picture_pages
end
class PicturePage < ActiveRecord::Base
has_one :page, :as =>:pagetype
has_one :book, :through => :pages
accepts_nested_attributes_for :page
end
class Page < ActiveRecord::Base
belongs_to :book
belongs_to :pagetype, :polymorphic => true, :dependent => :destroy
end
まずはsaveメソッドを使って……。
b = Book.first
params = { "page_attributes"=> { "number"=>"1" }}
p = b.picture_pages.new(params)
p.save
...期待どおりに機能します。Rails は自動的に新しい PicturePage を作成し、対応するページ結合モデルに "number" 属性が割り当てられます。完全。しかし、私がこれを行うと:
b = Book.first
params = { "page_attributes"=> { "number"=>"1" }}
p = b.picture_pages.create(params)
... Rails は 2 つの結合モデルを作成します。1 つは完全に空で、もう 1 つは number 属性を持ちます。どうしてこれなの?
Book モデルで accept_nested_attributes_for を使用する場合、これは大きな問題です。Book モデルは、作成中の PicturePage モデルで自動的に「作成」を呼び出すためです。
任意のヒント?これはRailsのバグですか?