Skip to content

Instantly share code, notes, and snippets.

@pjbelo
Last active July 12, 2018 19:50
Show Gist options
  • Save pjbelo/ddba81dcf16659b87e7b0c9da8707de1 to your computer and use it in GitHub Desktop.
Save pjbelo/ddba81dcf16659b87e7b0c9da8707de1 to your computer and use it in GitHub Desktop.
before delete/destroy check for restrict dependents [rails]
# Rails
# to use globally, put in class ApplicationRecord
# before delete/destroy check for restrict dependents
# given an object, iterate its associations, and check if the restricted ones are empty or not.
def has_no_restrict_dependent?
self.class.reflect_on_all_associations.all? do |assoc|
( ([:restrict_with_error, :restrict_with_exception].exclude? assoc.options[:dependent]) ||
(assoc.macro == :has_one && self.send(assoc.name).nil?) ||
(assoc.macro == :has_many && self.send(assoc.name).empty?) )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment