In several work scenarios we need a to create a parent-child relationship on a single model. So, it could be category and subcategory structure in an e-commerce site, or page and sub-page in a CMS. We will use category for our example. We will first generate our category model.
We need another model where we define the parent and child relationship of category model with itself. We will call this model category_relationship.
In our category_relationship model, we will now define fields – category_id and child_id. child_id is the reference field for storing the id of the child category. We will define a belongs_to relationship for the parent on the category model and another belongs_to relationship for the child on the same model.
In our category model, we will define relationships between parent and child. So, has_many and belongs_to relationships, both are made on the same model, and the reference happens via inverse_of.
Let’s create some category data.
We called our relationship parent_category and child_category. So we will use these terms to create and traverse the tree.
Let’s see the result of the relationships we just created. First, we will check the parent.
Then, we will check the child. Note that this returns an array, because of the has_many relationship.