문제

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?

도움이 되었습니까?

해결책

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)

다른 팁

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top