That title sounds weird, so let me try to explain what it is I’m trying to accomplish.
Let’s say I have a Category model, and the structure looks a little like this:
categories
id
name
parent_id
I also have a model for articles
articles
id
category_id
If I have a category named “News” with id: 1, and then a subcategory for it named “World News” with the id: 2 and parent_id: 1, if I have an article with category_id: 1 and another article with category_id: 2, I would like to be able to do something like:
category = Category.find 2 # This is the subcategory
category.articles # => Shows just the article belonging to that category
And
category = Category.find 1 # This is the parent category
category.articles # => Shows BOTH articles, the one for the child and the one for parent
Does that make sense?
What you are looking for is a tree structure for your categories. Using
parent_idis the most obvious way to implement it, but it gets complicated when you want to query children.A better solution is to use a nested set, which adds a bit of complication on insert/delete but pays off with very simple queries.
You can do the research to implement this, but as with a lot of things in rails, it’s a solved problem. Use awesome_nested_set which will take care of all of this for you.
Once you have installed the gem, create this migration:
Then add this line to your model:
You can use a query like this to get all articles: