我很难理解为什么“保存”和“创建”在使用带有accepts_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
首先,使用保存方法....
b = Book.first
params = { "page_attributes"=> { "number"=>"1" }}
p = b.picture_pages.new(params)
p.save
......事情就像你所期望的那样工作。Rails 将自动创建一个新的 PicturePage,并带有相应的 Page 连接模型,并分配有“数字”属性。完美的。但如果我这样做:
b = Book.first
params = { "page_attributes"=> { "number"=>"1" }}
p = b.picture_pages.create(params)
... Rails 将创建两个连接模型,一个完全为空,一个具有 number 属性。为什么是这样?
如果我想在书本模型上使用accepts_nested_attributes_for,这是一个主要问题,因为书本模型将在它正在创建的图片页面模型上自动调用“创建”。
有小费吗?这是Rails中的错误吗?