Skip to content

Instantly share code, notes, and snippets.

@ckdake
Created January 18, 2011 16:55
Show Gist options
  • Save ckdake/784743 to your computer and use it in GitHub Desktop.
Save ckdake/784743 to your computer and use it in GitHub Desktop.
find_or_create_tree_by_name
# Addon for classes using https://github.com/stefankroes/ancestry
# Create the full tree for this root/parent/child if it doesnt yet exist
# .save! is required to generate ancestry fields so that .children works
def self.find_or_create_tree_by_name(root_name = nil, parent_name = nil, child_name = nil)
if root_name.present?
root = self.find_or_create_by_name(root_name)
root.save!
if parent_name.present?
parent = root.children.find_or_create_by_name(parent_name)
parent.save!
if child_name.present?
child = parent.children.find_or_create_by_name(child_name)
child.save!
child
else
parent
end
else
root
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment