我正在使用 Rails 5、PostgreSQL。我需要使用 postgres DATE_TRUNC 获取按 created_at 分组的用户数。 条件是在某个日期范围内创建的用户,并且在同一日期范围内有订单。
下面是导致 AmbiguousFunction 错误的代码
Spree::User.joins(:orders)
.where(spree_orders: { completed_at: params[:start_date]..params[:end_date] })
.order("DATE_TRUNC('day', 'created_at')")
.group("DATE_TRUNC('day', 'created_at')")
.count
start_date 和 end_date 参数如下:
params[:end_date] = Time.current.end_of_day
params[:start_date] = (Time.current - 200.days).beginning_of_day
出现以下错误
ActiveRecord::StatementInvalid: PG::AmbiguousFunction: ERROR: function date_trunc(unknown, unknown) is not unique
甚至当我显式写入 spree_users.created_at 时,我也会遇到同样的错误。
是否有更好的方法来实现此错误的要求或解决方案?
最佳答案
ActiveRecord::StatementInvalid: PG::AmbiguousFunction
当我们的查询包含一个可能属于多个表的列名时,就会出现此错误。例如,我们有两个表,User
和 Company
,它们都有一个名为 name
的列。现在,以下查询会引发类似于您所面临的错误:
User.joins(:companies).where("name = ABC")
发生这种情况是因为我们没有指定在哪个表中搜索 name
。因此,ActiveRecord
变得困惑,无法创建唯一的查询。
在上述情况下,只需在 order
和 group 中使用的
查询:created_at
列名前添加 spree_users
即可解决错误
Spree::User.joins(:orders)
.where(spree_orders: { completed_at: params[:start_date]..params[:end_date] })
.order("DATE_TRUNC('day', 'spree_users.created_at')")
.group("DATE_TRUNC('day', 'spree_users.created_at')")
.count
关于ruby-on-rails - Rails,按 created_at day 分组的用户数 - PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54747157/