以循环为例dependent: :destroy
issue:
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
or after_destroy
手动销毁关联的对象而不是使用dependent: :destroy
机制。即便是GitHub 中为此打开了问题 https://github.com/rails/rails/issues/13609有几个人推荐了这种解决方法。
不幸的是,我什至无法让该解决方法发挥作用。这就是我所拥有的:
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
。这样就形成了一个循环。
如果循环的一侧只有一个回调,您可以替换其中之一dependent: :destroy
with dependent: :delete
class User < ActiveRecord::Base
# delete prevents Staff's :destroy callback from happening
has_one: :staff, dependent: :delete
has_many :other_things, dependent: :destroy
end
class Staff < ActiveRecord::Base
# use :destroy here so that other_things are properly removed
belongs_to :user, dependent: :destroy
end
只要一侧不需要其他回调来触发,对我来说效果很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)