ruby-on-rails - 在rails postgres上按字段分组结果
问题描述
我目前正在研究 rails,我正在尝试将查询结果按field
.
查询由以下人员创建:
@orders = Order.includes(:product).where(user_id: current_user.id, paid: 0).group(:product_id)
它在 sqlite (dev env) 上运行良好,但在生产 (postgreSQL) 上会引发致命错误。
错误是:
ActionView::Template::Error (PG::GroupingError: ERROR: column "orders.id" must appear in the GROUP BY clause or be used in an aggregate function
嗯..我在这里做错了什么?谢谢
解决方案
如果要在 postgres 中分组,则需要直接选择该列,或者需要调用使用该列的聚合函数。Count
就是这样一个聚合函数,你可以在 Rails 中通过
@product_counts = Order.where(user: current_user, paid: 0).group(:product_id).count
Postgres 自动Count
在您分组的列上执行,product_id
在这种情况下。这会给你一个像这样的哈希:
{ product_id => count }
有关更多信息,请参见此处:https ://www.tutorialspoint.com/postgresql/postgresql_group_by.htm
推荐阅读
- python - Visual Studio Code 调试 python 脚本,文件路径中带有 & 符号
- java - 正则表达式多行检查样式模块不起作用
- android - ListView 项适配器无法单击
- json - 带有漂亮链接的 Woocommerce 结帐“意外令牌”
- php - 使用链接或按钮下载 Blob 文件
- javascript - 打开和关闭灯箱
- sql - Entity Framework Core PostgreSQL 插入 -2147482647 Id
- c# - 如何让 CefSharp 在 vs 通用库中使用配置 AnyCPU
- ios - 在 CollectionView Swift 上显示 Gif
- java - void 方法不能返回值 -Java