Created
          January 18, 2011 16:55 
        
      - 
      
- 
        Save ckdake/784743 to your computer and use it in GitHub Desktop. 
    find_or_create_tree_by_name
  
        
  
    
      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
    
  
  
    
  | # 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