When dealing with complex associations that are slow to index via standard ActiveRecord includes, use Chewy Crutches. Crutches allow you to fetch data for an entire batch of objects using a single, lightweight query (e.g., using .pluck) and then map that data to the objects during the indexing process.
This can increase indexing performance significantly by avoiding expensive object initialization for associated records.
class ProductsIndex < Chewy::Index
index_scope Product
crutch :categories do |collection|
# Fetch data for the whole batch efficiently
data = ProductCategory.joins(:category)
.where(product_id: collection.map(&:id))
.pluck(:product_id, 'categories.name')
# Format as a lookup hash: { product_id => [category_names] }
data.each.with_object({}) { |(id, name), result| (result[id] ||= []).push(name) }
end
field :name
# Access crutch data in the value proc
field :category_names, value: ->(product, crutches) { crutches[:categories][product.id] }
end