You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Arel实现返回ActiveRelation的带最高价格水果查询Scope

实现带最高价格的Fruit查询Scope

需求说明

需要实现一个查询Scope,获取符合条件的水果数据时附带当前结果集的最高价格,示例调用:

Fruit.with_max_price.where("date > '2022'")

约束条件

  • 必须使用Arel构建查询
  • 实现为返回ActiveRelation的Scope,支持链式调用

已知表结构

idnameprice
1apple12
2banana6
3orange18

期望输出

idnamepricemax_price
1apple1218
2banana618
3orange1818

解决方案

在Fruit模型中添加以下Scope实现:

class Fruit < ApplicationRecord
  scope :with_max_price, -> do
    fruits_table = arel_table
    max_price_subquery = fruits_table.project(fruits_table[:price].maximum.as('max_price'))

    select(
      fruits_table[Arel.star],
      Arel.sql("(#{max_price_subquery.to_sql}) AS max_price")
    )
  end
end

代码说明

  1. Arel表实例:通过arel_table获取Fruits表的Arel对象,避免硬写SQL字段名,提升查询安全性。
  2. 动态最高价格子查询:子查询会自动继承当前查询链中的所有条件(比如后续的where过滤),计算出对应结果集的最高价格。
  3. 合并字段返回:使用select将原表所有字段和子查询的最高价格字段合并,返回的ActiveRelation可以继续链式调用其他查询方法。

验证

执行示例调用后,返回的每条记录都会包含max_price字段,值为当前结果集中的最高价格,与期望输出一致。


内容的提问来源于stack exchange,提问作者Quentin Gaultier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 15:15:43