Created
November 8, 2010 06:26
-
-
Save rubenrails/667433 to your computer and use it in GitHub Desktop.
Returns whether an instance can be deleted or not.
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
require 'instance_helpers' | |
ActiveRecord::Base.send(:include, InstanceHelpers) |
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
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