Created
August 26, 2012 00:40
-
-
Save hartct/3472835 to your computer and use it in GitHub Desktop.
Check if a record can be deleted when using foreigner gem
This file contains 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
module ActiveRecord | |
class Base | |
def can_delete? | |
this_model_name = self.class.name | |
associations = Kernel.const_get(this_model_name).reflect_on_all_associations | |
has_one_models = associations.map{ |x| x.name.to_s if x.macro == :has_one }.compact | |
has_one_models.each do |child| | |
if self.send(child).present? | |
return false | |
end | |
end | |
has_many_models = associations.map{ |x| x.name.to_s.pluralize if x.macro == :has_many }.compact | |
has_many_models.each do |child| | |
if self.send(child).present? && self.send(child).count > 0 | |
return false | |
end | |
end | |
true | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment