Everyday Rails

Trees and taxonomies with Ancestry

By Aaron Sumner, November 16, 2010.

Ancestry is a handy gem for building tree structures or taxonomies in your Rails applications. It’s similar to the likes of the acts_as_tree plugin (see the Railscasts tutorial). The project wiki has several ideas for ways to put Ancestry to use; in this post I’ll cover a couple of basic uses to get you rolling with some common applications of the gem.

Installation

Follow the instructions provided in Ancestry’s README to add it to your application. It’s very straightforward: Install the gem, generate and run a migration, and add has_ancestry to any model you’d like to turn into a tree. For example, you might have a hierarchy of categories; once you’ve installed Ancestry this can be created with

  # app/models/category.rb

  class Category < ActiveRecord::Base
    has_ancestry
    
    # rest of model
  end

Built-in functionality

The nice thing about Ancestry is how easy it makes it to work with a given object in your tree, its parents, and its children. It does this through more than 20 useful instance methods and several scopes. Among the ones you may want to start with:

  • Roots: To get a collection of the Category taxonomy’s top-level nodes, just call Category.roots.
  • Children: Pretty straightforward; @category.children gives you a collection of a given category’s subcategories.
  • Ancestors: A category’s ancestry—its parent, grandparent, and on back—is accessible with @category.ancestors.
  • Parent: You’ve probably guessed it; @category.parent will give you the category’s parent category. Useful if you want to include a back link in your view.

A practical use of Ancestry is to help visitors navigate your site through breadcrumbs. This is easy to add to your view:

  # app/views/category.show.haml

  %div#breadcrumbs
    = link_to 'Home', categories_url
    &gt;
    - @category.ancestors.each do |a|
      = link_to a.name, a
      &gt;

That’s all there is to it to help your site visitors navigate your content more easily.

What do you think? Follow along on on Twitter or Facebook to let me know what you think and catch my latest posts. Better yet, subscribe to my newsletter for updates from Everyday Rails, book picks, and other thoughts and ideas that didn't quite fit here.

Test with confidence!

If you liked my series on practical advice for adding reliable tests to your Rails apps, check out the expanded ebook version. Lots of additional, exclusive content and a complete sample Rails application.

Newsletter

Ruby on Rails news and tips, and other ideas and surprises from Aaron at Everyday Rails. Delivered to your inbox on no particular set schedule.