如何从祖父母

时间:2016-04-30 03:02:25

标签: ruby-on-rails rails-activerecord

假设我们有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

但是,如果您已保存ParentChild,则无法通过保存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 }。)

0 个答案:

没有答案