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

如何将指定PostgreSQL SQL查询改写为Rails Active Record语句

对应Rails Active Record查询写法

首先是和你给出的SQL逻辑1:1对齐的写法:

User.select("objects.*, (objects.value)->>0 AS first_value")
    .from("users, jsonb_each(hit->'opportunity') objects")
    .where("objects.key::text ~ ?", '^[0-9]{0,4}_pct$')
    .where("((objects.value)->>0)::numeric >= ?", 0.5)

写法说明

  • select部分给(objects.value)->>0加了别名first_value,你可以直接从返回的Active Record实例中调用.first_value拿到对应结果,不需要额外解析
  • from部分完全复现原SQL的数据源配置,将jsonb_each生成的临时表命名为objects,和users表做关联
  • 所有where条件都用占位符传参,避免SQL注入风险,逻辑和原SQL完全一致

如果你需要保留users表的字段,或者希望写法更符合Rails关联规范,可以用LATERAL JOIN版本:

User.joins("JOIN LATERAL jsonb_each(hit->'opportunity') objects ON true")
    .select("users.*, objects.*, (objects.value)->>0 AS first_value")
    .where("objects.key::text ~ ?", '^[0-9]{0,4}_pct$')
    .where("((objects.value)->>0)::numeric >= ?", 0.5)

内容的提问来源于stack exchange,提问作者Dok Nabaku

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:27:03