假设我们有3个ActiveRecord类:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
has_many :grandchildren
end
class Grandchild < ActiveRecord::Base
belongs_to :child
end
在Child
关联中构建Parent#children
时,保存Parent
会创建Child
:
parent = Parent.new
parent.children.build
parent.save # creates a Parent and a Child
如果您有Grandchild
,它也会保存它:
parent = Parent.new
parent.children.build
parent.children.first.grandchildren.build
parent.save # creates a Parent, a Child, and a Grandchild
但是,如果您已保存Parent
和Child
,则无法通过保存Grandchild
来创建Parent
:
parent = Parent.new
parent.children.build
parent.save # creates a Parent and a Child
parent.children.first.grandchildren.build
parent.save # does nothing...
有没有办法让parent.save
保存Grandchild
?
(这不仅仅是一个理论问题......我实际上有理由这样做,我宁愿不必致电parent.children.each {|c| c.save }
。)