Implementing hierarchical categories in Ruby on Rails

Photo by David Herron on Unsplash

Whenever you’re building a startup application, whether it is a blog of yours, or a forum for your network or an e-commerce store. it is often the case that you’re going to be needing a some sort of a hierarchical categories set-up in your application.

Through this article, you are going to be learning a very efficient way of implementing your hierarchical categories in such a way; that no third-party gem is used whatsoever. it will all be done using solid ruby on rails structure and code. Before we begin, it is critical to vision our final outcome.

Imagine you are building an e-commerce store where you have categories and subcategories as such;

To reflect this structure in our models, we are going to use what’s called a self-joining relation. Where the Category table references itself using a foreign-key. Here is what your Category and Product models should look like:

Class Category < ActiveRecord::Base 
has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id'
has_many :products

This is an extremely powerful pattern that enables you to build any depth of hierarchical structure, in addition to saving you the resources to query back and forth to query different tables from the DB. Next, we are going to see how to seed this model with dummy data.

In our seeds.rbwe are going to seed our database as such;

#Parent Category
Category.create(name: "Apparel Store", parent_id: nil)

Our Parent Category ‘Apparel Store’ doesn’t have a parent. hence, parent_id: nil. now in order to reference children subcategories to its parents, we need to assign the parents primary keys to its children parent_id notice how we assigned a parent_id: 1 to both ‘Shoes’ and ‘Clothes’ referencing ‘Apparel Store’ primary key. the same thing went with the Children of subcategories where they referenced their parent_id's by their parents’ primary keys.

Upon seeding, you can make sure your structure works as planned by testing it in your rails console.

Thank you. if you have any further questions or feedback, feel free to leave a comment.

Happy coding!

I build SaaS applications using Ruby on Rails.