Last active
July 12, 2018 19:50
-
-
Save pjbelo/ddba81dcf16659b87e7b0c9da8707de1 to your computer and use it in GitHub Desktop.
before delete/destroy check for restrict dependents [rails]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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