Check all associations before destroy in rails

后端 未结 2 744
礼貌的吻别
礼貌的吻别 2020-12-28 23:24

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:

2条回答
  •  梦谈多话
    2020-12-28 23:25

    Create a module into app/models/concerns/verification_associations.rb wiht:

    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
    

    Create a new translation key into app/config/locales/rails.yml

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

    In your models include the module:

    class Model < ActiveRecord::Base
      include VerificationAssociations
    end
    

提交回复
热议问题