【发布时间】:2011-06-20 20:56:23
【问题描述】:
根据docs,在关联上设置:autosave => false 不应在保存父级时保存这些关联。这似乎对我不起作用。我刚刚创建了一个香草 Rails 3.0.8 应用程序,这就是我得到的:
class Foo < ActiveRecord::Base
has_many :bars, :autosave => false
accepts_nested_attributes_for :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
f = Foo.new :name => 'blah', :bars_attributes => [{:name => 'lah'},{:name => 'lkjd'}]
f.save
f.bars
=> [#<Bar id: 1, name: "lah", foo_id: 1, created_at: "2011-06-20 20:51:02", updated_at: "2011-06-20 20:51:02">, #<Bar id: 2, name: "lkjd", foo_id: 1, created_at: "2011-06-20 20:51:02", updated_at: "2011-06-20 20:51:02">]
什么?为什么要保存bars?
我觉得我正在服用疯狂的药丸!我错过了什么?
更新:似乎accepts_nested_attributes_for 会自动保存子项,即使它们不是使用嵌套属性功能构建的。它认为这是一个错误。
【问题讨论】:
-
运行给定代码后
f.bars.first.new_record?的输出是什么? -
我在上面输出了
f.bars。很明显,new_record?将返回 false,因为它已使用 ID 持久化。同样,这只发生在使用accepts_nested_attributes_for时
标签: ruby-on-rails activerecord autosave