Skip to content

Instantly share code, notes, and snippets.

@hartct
Created August 26, 2012 00:40
Show Gist options
  • Save hartct/3472835 to your computer and use it in GitHub Desktop.
Save hartct/3472835 to your computer and use it in GitHub Desktop.
Check if a record can be deleted when using foreigner gem
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