Check all associations before breaking in rails

I have an important model in my application with many associations. If I want to check all the links in the before_destroy callback, I will need 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 checks at once? Thanx!

+8
ruby-on-rails associations
source share
2 answers

You can pass the parameter :dependent => :restrict for calls to has_many :

 has_many :models, :dependent => :restrict 

Thus, you can only destroy an object if no other related objects are attached to it.

Other options:

  • :destroy - destroys every related object that calls their destroy method.
  • :delete_all - Deletes each associated object without calling the destroy method.
  • :nullify - sets the foreign keys of related objects to NULL without calling their save callbacks.
+23
source share

Create a module in app / models / issues / 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 in app / config / locales / rails.yml

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

Your model includes a module:

 class Model < ActiveRecord::Base include VerificationAssociations end 
+1
source share

All Articles