[英]Including association to active model serializer
我在控制器的索引方法中有多個數據庫查詢問題。 基本上,我正在渲染一個首先由ActiveModelSerializer序列化的JSON,請參見下文:
def index
packs = Pack.editable_by(current_user)
render json: packs, each_serializer: PackSerializer, include: :documents, root: false
end
因此,packs數組中的每個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
我認為在查詢中包含documents
就足夠了,所以
def index
packs = Pack.editable_by(current_user).includes(:documents)
render json: packs, each_serializer: PackSerializer, root: false
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.