Question

I have 2 models: Post and Category

Category has_many Posts,

Post belongs_to Category,

Category model uses ancestry gem,

the goal is to get all posts that belongs_to the given category and to all its ancestors. Should I simply use a loop for this or there is some smarter way to do this?

Was it helpful?

Solution

You can use this to get the posts that belong the given category or one of its ancestors:

Post.where(:category_id => category.path_ids)

OTHER TIPS

The ancestry gem passes nested hash objects when you use it, so you can select a master node and then use the hash object as a way to iterate through & get all of its ancestors:

#controller
@category = Category.find params[:id]

#view
render partial: "category", locals: { category: @category }

#partial
<ol class="categories">
    <% category.each do |category, sub_item| %>
        <li>
            <%= category.name %>
            <% if category.has_children? %>
            <%= render partial: "category", locals: { category: category.children } %>
            <% end %>
        </li>
    <% end %>
</ol>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top