在 Rails 中销毁之前检查所有关联 [英] Check all associations before destroy in rails
本文介绍了在 Rails 中销毁之前检查所有关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用程序中有一个重要的模型,有很多关联.如果我想检查 before_destroy 回调中的所有引用,我必须执行以下操作:
I have an important model in my application, with many associations. If I want to check all the references in a before_destroy callback, i'd have to do something like:
has_many :models_1
has_many :models_2
mas_many :models_3
....
....
has_many :models_n
before_destroy :ensure_not_referenced
def :ensure_not_referenced
if models_1.empty? and models_2.empty? and models_3.empty? and ... and models_n.empty?
return true
else
return false
errors.add(:base,'Error message')
end
end
问题是,有没有办法一次执行所有验证?谢谢!
The question is, is there a way to perform all the validations at once? Thanx!
推荐答案
你可以通过 :dependent =>
选项:has_many
调用的 :restrict
You can pass the :dependent => :restrict
option to your has_many
calls:
has_many :models, :dependent => :restrict
这样,只有在没有其他关联对象引用它的情况下,您才能销毁该对象.
This way, you will only be able to destroy the object if no other associated objects reference it.
其他选项是:
:destroy
- 销毁所有调用其destroy
方法的关联对象.:delete_all
- 删除所有关联对象调用它们的destroy
方法.:nullify
- 将关联对象的外键设置为NULL
无需调用它们的保存回调.
:destroy
- destroys every associated object calling theirdestroy
method.:delete_all
- deletes every associated object without calling theirdestroy
method.:nullify
- sets the foreign keys of the associated objects toNULL
without calling their save callbacks.
这篇关于在 Rails 中销毁之前检查所有关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文