繁体   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