dependent: :destroy
以循环问题为例:
class User < ActiveRecord::Base
has_one: :staff, dependent: :destroy
end
class Staff < ActiveRecord::Base
belongs_to :user, dependent: :destroy
end
如果我打电话user.destroy
,关联的staff
也应该被销毁。相反,调用staff.destroy
也应该破坏关联user
。
这在 Rails 3.x 中效果很好,但是在 Rails 4.0(并在 4.1 中继续)中行为发生了变化,因此形成了一个循环,最终你会得到一个错误,“堆栈级别太深”。before_destroy
一种明显的解决方法是使用或after_destroy
手动销毁关联对象而不是使用该dependent: :destroy
机制来创建自定义回调。甚至GitHub 中针对这种情况打开的问题也有几个人推荐了这种解决方法。
不幸的是,我什至无法让这种解决方法发挥作用。这就是我所拥有的:
class User < ActiveRecord::Base
has_one: :staff
after_destroy :destroy_staff
def destroy_staff
staff.destroy if staff and !staff.destroyed?
end
end
这不起作用的原因是它staff.destroyed?
总是返回false
。于是就形成了一个循环。