简体   繁体   English

在Rails Postgres上按字段分组结果

[英]group results by field on rails postgres

I'm studying rails at the moment and i'm trying to group results of a query by field . 目前,我正在研究Rails,并尝试按field对查询结果进行分组。

the query is being created by: 查询是由以下人员创建的:
@orders = Order.includes(:product).where(user_id: current_user.id, paid: 0).group(:product_id)

It works fine on sqlite (dev env) but it throws a fatal error while on production (postgreSQL). 它在sqlite(dev env)上运行良好,但在生产(postgreSQL)时抛出致命错误。

Error is: 错误是:

ActionView::Template::Error (PG::GroupingError: ERROR:  column "orders.id" must appear in the GROUP BY clause or be used in an aggregate function

Hmm.. what am i doing wrong here? 嗯..我在这里做错了什么? Thanks 谢谢

If you want to group in postgres, you need to either directly select that column or you need to call an aggregate function that uses this column. 如果要对postgres进行分组,则需要直接选择该列,或者需要调用使用该列的聚合函数。 Count is such an aggregate function and you can achieve that in Rails via Count是一个聚合函数,您可以通过以下方式在Rails中实现

@product_counts = Order.where(user: current_user, paid: 0).group(:product_id).count

Postgres automatically executes Count on the column you grouped by, which is product_id in this case. Postgres自动在您分组的列上执行Count ,在本例中为product_id This will give you a hash like this: 这将为您提供这样的哈希值:

{ product_id => count }

For more information, see here: https://www.tutorialspoint.com/postgresql/postgresql_group_by.htm 有关更多信息,请参见此处: https : //www.tutorialspoint.com/postgresql/postgresql_group_by.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM