Skip to content

Instantly share code, notes, and snippets.

@coryodaniel
Created February 13, 2009 04:52
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 coryodaniel/63053 to your computer and use it in GitHub Desktop.
Save coryodaniel/63053 to your computer and use it in GitHub Desktop.
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