Reducing N+1 queries by eager loading

未關閉
#485 10 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
5/5
預估耗時
一週以上
新手友好度
25/100
Issue 類型
功能
描述清晰度
需要釐清
活躍度
停滯
技術堆疊
rails, ruby

研究方向

首先追蹤 resources controller、records 方法,以及針對 ProjectResource 和 CompanyResource 所描述的 include 處理。重現 /api/projects?include=company 的情況,並將其與 company.subscription 進行比較;完成的標準是:計算屬性使用的相依資料會被 eager load,而不要求用戶端請求該關聯。

由索引模型根據 Issue 內容生成。

描述

Type: Maintenance

I read through the documentation and couldn't find a built-in solution to this problem. When certain models are serialized we need to make sure that the query to retrieve that entity always adds an includes to avoid all the lazy loaded N+1 queries. We can do this via records as long as the request is on the resources controller. If it's not then I couldn't see a place to extend it.

Let me give an example

class ProjectResource
  has_one :company
end
class CompanyResource
  attribute :plan_start_at

  def plan_start_at
    @model.subscription.created_at
  end
end

As you'll notice each time a company is rendered it is going to retrieve a value out of it's subscription. However, the problem comes in when we request a URL like this

/api/projects?include=company

It's using the records method off of the projects resource and even when it goes to process the include on company it's not calling records on the company resource so we end up with a separate query for every companies subscription.

Now, from what I can tell maybe this is supposed to be taken care of by also requesting the subscription like this

/api/projects?include=company,company.subscription

However this doesn't completely work since I don't need the subscription object and requesting the subscription isn't a concern of the client (since we simply need the subscription in order to calculate a property on the company.)

主要語言
Ruby
星號
2.3k
分支
546
PR 合併指標
30 天內沒有已合併 PR

貢獻指南

這個儲存庫沒有索引到貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

JSONAPI-Resources/jsonapi-resources 的其他 Issue

查看 JSONAPI-Resources/jsonapi-resources 的全部 Issue

相似的 Issue

更多 Ruby Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。