Max Filippov
Max Filippov

Reputation: 2072

Rails ancestry gem + has_many

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?

Upvotes: 1

Views: 602

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

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>

Upvotes: 1

Baldrick
Baldrick

Reputation: 24340

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)

Upvotes: 1

Related Questions