Search code examples
ruby-on-railsruby-on-rails-3ancestry

Rails ancestry: Get children records of ancestry model


I've two models:

Post
 - category_id

Category (ancestry model)

The category tree looks for example like this:

- Root Category

  - Sub Category

Now lets say a post gets categorized to Sub Category. I'm in the Root Category and i would like to see all posts which are in Sub Category as well. Is it possible to get these as well with ancestry?

The category tree always has just one nested level so maybe ancestry is anyways too much..

Thanks in advance

Working example for just one nested level

@category = Category.find(params[:id])
category_ids = @category.children.map(&:id) << @category.id
category_ids = category_ids.join(",")
@posts = Post.recent.where("category_id IN (#{category_ids})").page(params[:page])

Solution

  • I suggest that the following would do the trick:

    Post.where(category_id: @category.subtree_ids)
    

    And would also probably be the most efficient way without doing something really horrible.