Created
February 13, 2009 04:52
-
-
Save coryodaniel/63053 to your computer and use it in GitHub Desktop.
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
def check_delete_constraints | |
model.relationships.each do |rel_name, rel| | |
debugger if $CASE_DEBUG | |
#Only look at relationships where this model is the parent | |
next if rel.parent_model != model | |
#Don't delete across M:M relationships, instead use their anonymous 1:M Relationships | |
next if rel.is_a?(DataMapper::Associations::RelationshipChain) | |
children = self.send(rel_name) | |
case rel.delete_constraint | |
when nil, :protect | |
# only prevent deletion if the resource is a parent in a relationship and has children | |
if children && children.respond_to?(:empty?) && !children.empty? | |
DataMapper.logger.info("Could not delete a #{self.class} a child record exists #{children.first.class}") | |
throw(:halt,false) | |
end | |
when :destroy! | |
if children && children.respond_to?(:destroy!) | |
# not sure why but this lazy_load is necessary | |
# otherwise children will not be deleted with destroy! | |
children.lazy_load | |
children.destroy! | |
end | |
when :destroy | |
if children && children.respond_to?(:each) | |
children.each{|child| child.destroy} | |
end | |
when :set_nil | |
if children && children.respond_to?(:each) | |
children.each do |child| | |
child.class.many_to_one_relationships.each do |mto_rel| | |
child.send("#{mto_rel.name}=", nil) if child.send(mto_rel.name).eql?(self) | |
end | |
end | |
end | |
end # case | |
end # relationships | |
end # check_delete_constraints |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment