在将其销毁之前,请检查所有关联

问题描述

| 我的应用程序中有一个重要的模型,具有许多关联。如果我想检查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
问题是,有没有一种方法可以一次执行所有验证? 谢谢!     

解决方法

        您可以将
:dependent => :restrict
选项传递给
has_many
呼叫:
has_many :models,:dependent => :restrict
这样,只有在没有其他关联对象引用该对象的情况下,您才可以销毁该对象。 其他选项是:
:destroy
-销毁所有关联对象,调用其
destroy
方法。
:delete_all
-删除每个关联的对象而不调用其their5ѭ方法。
: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