从group_by中的每个组中检索单个记录?

时间:2014-02-26 06:47:09

标签: ruby-on-rails ruby postgresql

我正努力让每个月的企业员工获得最高分。

架构如下所示:

class Business < ActiveRecord::Base
 has_many :employees
 has_many :placements, through: :employees

class Employee < ActiveRecord::Base
 attr_accessible :name
 belongs_to :business
 has_many :placements

class Placement < ActiveRecord::Base
 attr_accessible :month, :employee_id, :points
 belongs_to :employee

我尝试了以下内容:

@business.placements.includes(:employee).group(:month).order('points DESC').map(&:employee)

但是我收到了PostgreSQL group_by错误:

: SELECT "placements".* FROM "placements" INNER JOIN "employees" ON "placements"."employee_id" = "employees"."id" WHERE "employees"."business_id" = 43 GROUP BY month ORDER BY points DESC
ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "placements.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "placements".* FROM "placements" INNER JOIN "employee...

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

当您对任何列进行分组时,您需要选择其中的group_by或者具有某些聚合函数。默认情况下,AR会撤回所有列,因此您可能希望使用.select

来限制该列