Eager loading ancestors tree for multiple leaves

230 Views Asked by At

I am looking for an efficient way to retrieve the category tree to display along with the results for product search.

A product can have one or more categories (many-to-many relationship to leaf categories). The idea is to reconstruct the ancestor tree from the unique id for each category found. I am currently using the ancestors helper provided by acts-as-nested-set gem, however that has the disadvantage of doing point-queries for each category. Ideally it would retrieve all ancestors for the given set of categories in a single query. Any ideas?

def search
    @search_result = @store.products.includes(:categories).where("title LIKE ?  ", "%#{params[:query]}%")

    # retrieving all leaf categories for the products above
    unique_ids = @search_result.map { |p| p.categories.map { |c| c.id }}.flatten!.uniq!
    @leaf_categories = Category.where(id: unique_ids).map { |c| c.ancestors }
end
1

There are 1 best solutions below

0
On

Try to eager load ancestors of categories as well.

@search_result = @store.products.includes(:categories=>[:ancestors]).where("title LIKE ? ", "%#{params[:query]}%")