在rails中销毁之前检查所有关联

我的应用程序中有一个重要的模型,有许多关联。 如果我想检查before_destroy回调中的所有引用,我必须执行以下操作:

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 

问题是,有没有办法立即执行所有validation? 感谢名单!

您可以将:dependent => :restrict选项传递给has_many调用:

 has_many :models, :dependent => :restrict 

这样,如果没有其他关联对象引用它,您将只能销毁该对象。

其他选择是:

  • :destroy – 销毁调用其destroy方法的每个相关对象。
  • :delete_all – 删除每个关联的对象而不调用其destroy方法。
  • :nullify – 将关联对象的外键设置为NULL 而不调用其保存回调。

在app / models / concerns / verification_associations.rb中创建一个模块:

 module VerificationAssociations extend ActiveSupport::Concern included do before_destroy :check_associations end def check_associations errors.clear self.class.reflect_on_all_associations(:has_many).each do |association| if send(association.name).any? errors.add :base, :delete_association, model: self.class.model_name.human.capitalize, association_name: self.class.human_attribute_name(association.name).downcase end end return false if errors.any? end end 

在app / config / locales / rails.yml中创建一个新的翻译密钥

 en: errors: messages: delete_association: Delete the %{model} is not allowed because there is an association with %{association_name} 

在您的模型中包括模块:

 class Model < ActiveRecord::Base include VerificationAssociations end