Search code examples
ruby-on-railshas-manyancestry

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?


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)