检查所有关联之前,摧毁轨道 [英] Check all associations before destroy in 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!
推荐答案
您可以通过:依赖=> :限制
选项,你的的has_many
调用:
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.
其他选项是:
-
:摧毁
- 摧毁每一个相关联的对象调用它们的摧毁
法 -
:DELETE_ALL
- 删除每个关联对象的没有调用它们的摧毁
方法。 -
:废止
- 关联对象的外键设置为NULL
< STRONG>无调用它们保存回调。
: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.
这篇关于检查所有关联之前,摧毁轨道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文