Search code examples
ruby-on-railsrubyeager-loadingactive-model-serializers

Active model Serializers not eager loading relationships


I'm using the Bullet gem to see where there are n+1 queries in my application. It's telling me to eager load my association taggings when calling my serializer. My code looks something like this:

render json: @products, each_serializer: ::V1::ProductSerializer, includes: [:taggings], links: links, status: :ok

But after I add that, i'm still getting the same warning from the Bullet gem. Which looks like this:

GET /api/v1/product_feed?state=CA&page=1
USE eager loading detected
  Product => [:taggings]
  Add to your finder: :includes => [:taggings]
Call stack
  /home/jay/current_projects/api/app/controllers/api/v1/products_controller.rb:111:in `product_feed'

Does anyone have any idea why the taggings table is not being eager loaded.


Solution

  • You need to include taggings in your query first then the serializer will be able to read the loaded records instead of separately asking for the taggings association record by record

    @products = Product.includes(:taggings)
    render json: @products, each_serializer: ::V1::ProductSerializer, includes: [:taggings], links: links, status: :ok