想要将我的表格与created_at
日期,user_id
,action
和trackable_type
分组。
但是按照查询分组不能为PG工作并给出错误。
PG::GroupingError: ERROR: column "activities.id" must appear in the GROUP BY...
activities = Activity.all.group("activities.created_at::date, activities.user_id, activities.action, activities.trackable_type")
因此按功能将activities.id
添加到组
activities = Activity.all.group("activities.created_at::date, activities.user_id, activities.action, activities.trackable_type, activities.id")
给出了puts "#{activities.map{|a| a.id}}"
[645, 646, 642, 643, 644]
正确的结果应该是
1 => [645, 646, 642], 2 => [643, 644]
使用:
ruby 1.9.3
rails 3.2.6
0.14.0
答案 0 :(得分:0)
您可以尝试使用select列表来缩小查询范围,然后您不需要将activities.id
添加到GROUP BY
子句中。
标准SQL要求SELECT
子句中的所有项都要聚合或包含在GROUP BY
子句中。默认情况下,Rails在ActiveRecord查询中执行SELECT *
,然后强制您在GROUP BY
中包含所有字段。限制SELECT
列表字段可能会有所帮助。
试试这个:
activities = Activity.all
.select(:created_at, :user_id, :action, :trackable_type)
.group("activities.created_at::date, activities.user_id, activities.action, activities.trackable_type")