Skip to content

Instantly share code, notes, and snippets.

@rubenrails
Created November 8, 2010 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubenrails/667433 to your computer and use it in GitHub Desktop.
Save rubenrails/667433 to your computer and use it in GitHub Desktop.
Returns whether an instance can be deleted or not.
require 'instance_helpers'
ActiveRecord::Base.send(:include, InstanceHelpers)
module InstanceHelpers
public
# Extends ActiveRecord. Returns false if an has any associated object.
# You can pass a list of association names to be ignored,
# e.g. @user.can_be_deleted?(:ignore => [:addresses, :phones])
def can_be_deleted?(options={})
options[:ignore] ||= []
# Check for single model associations using: present?
ho = self.class.reflect_on_all_associations :has_one
assocciated_model_names = ho.map{ |obj| obj.name } - options[:ignore]
return false if assocciated_model_names.any?{ |a| self.send(a).present? }
# Avoid DB overhead by using: count.zero? for collection associations
habtm = self.class.reflect_on_all_associations :has_and_belongs_to_many
hm = self.class.reflect_on_all_associations :has_many
aggregate_objs = habtm + hm
aggregate_obj_names = aggregate_objs.map{|obj| obj.name } - options[:ignore]
!aggregate_obj_names.any?{ |a| !self.send(a).count.zero? }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment