簡體   English   中英

ActiveRecord has_one 按日期排序

[英]ActiveRecord has_one with order by date

我正在嘗試建立一個 ActiveRecord 關系,其中我有一個has_one返回最新值:

class Check < ApplicationRecord
  has_many :counts
  has_one :latest_count, -> { order(created_at: :desc) }, class_name: 'Count'
end

想要這樣的原因是在查找latest_count時避免 N+1 查詢:

current_user.checks.preload(:latest_count)

我遇到的問題是預加載latest_count實際上會預加載所有計數並抓取 memory 中的最后一個。 即使在小范圍內,這也會導致問題,memory 膨脹和查詢時間都在迅速增加。 有沒有辦法設置這種關系,以便它只預加載最后一個? 我想到的唯一選擇是將latest_count_id添加到checks表中,並在創建新計數時對其進行更新。

創建新count時更新latest_count_id似乎效率不高。

您可以像這樣嘗試自定義SELECT

# Example code, may need to tweak a bit

class Check
  scope :preload_latest_count, -> {
    joins.lfet_joins(:counts)
         .order("checks.id, counts.created_at DESC")
         .select("DISTINCT ON (checks.id) checks.*, counts.value AS latest_count_value")
  }
end

checks = current.checks.preload_latest_count
check = checks.first
check.latest_count_value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM