活动模型序列化器不急于加载关系

Jay*_*Jay 3 ruby ruby-on-rails eager-loading active-model-serializers

我正在使用Bullet gem来查看应用程序中的n + 1个查询。它告诉我taggings在调用序列化程序时急于加载我的关联。我的代码如下所示:

render json: @products, each_serializer: ::V1::ProductSerializer, includes: [:taggings], links: links, status: :ok
Run Code Online (Sandbox Code Playgroud)

但是添加完之后,我仍然从Bullet gem得到同样的警告。看起来像这样:

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'
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么不急于加载标签表。

Van*_*kov 5

您需要首先在查询中包含标签,然后序列化程序将能够读取已加载的记录,而不是逐条记录地询问标签关联记录

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