包括与活动模型序列化器的关联

时间:2016-06-23 15:55:03

标签: ruby-on-rails json activerecord serialization

我在控制器的索引方法中遇到了多个数据库查询的问题。基本上,我正在渲染一个由ActiveModelSerializer首先序列化的JSON,见下文:

def index
  packs = Pack.editable_by(current_user)
  render json: packs, each_serializer: PackSerializer, include: :documents, root: false
end

所以,pack数组中的每个包都由它序列化。序列化程序本身依赖于关联(一个包可以有很多文档),这就是为什么我添加了include: :documents以便它被急切加载并避免N + 1查询。

不幸的是它没有用。

在这种情况下有谁知道如何避免N + 1查询?

PackSerializer大致如下所示:

class PackSerializer < ActiveModel::Serializer
  attributes #some attributes

  def doc_title
     @object.latest_document.title
  end

  ...

end




class Pack < ActiveRecord::Base

  ...

  def latest_document
    documents.where(is_published: true).order(:created_at).last
  end

  ...
end

1 个答案:

答案 0 :(得分:0)

我认为在查询之前包含documents就足够了,所以

def index
  packs = Pack.editable_by(current_user).includes(:documents)
  render json: packs, each_serializer: PackSerializer, root: false
end
相关问题