I'm using Ancestry gem to manage categories (Category model) in a hierarchical structure.

I need to query the Category to retrieve specific categories by their IDs and include all their ancestors in the result, if any.

I've implemented a solution, but I believe there might be a more efficient approach. Here's what I have so far:

ancestry_arr = specific_categories.pluck(:ancestry).uniq.compact

ancestry_ids = ancestry_arr.map do |string|
  string.scan(/\d+/).map(&:to_i)
end

result = specific_categories + Category.where(id: ancestry_ids.flatten)

Is there a more efficient and cleaner way to achieve this ?

I want to make sure I'm following best practices and optimizing my queries. Any suggestions or improvements would be greatly appreciated.

1

There are 1 best solutions below

0
On

Try this:

result = specific_categories + 
           Category.where(id: specific_categories.map(&:ancestor_ids).flatten.uniq)