okay. I solved by myself. The solution use facets
First of all, we need to add direct_category_id:
has category(:id), as: :direct_category_id, facet: true
After that, we need just to use
category_ids = products.facets[:direct_category_id].keys
categories = Category.where(id: category_ids)