2014-02-26 31 views
1

我正在努力讓每個月的業務員工在每個月的工作點中達到最高點。從group_by中的每個組檢索單個記錄?

的模式是這樣的:

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... 

任何幫助將不勝感激。

+0

,*始終顯示錯誤的確切文字*。在這種情況下,我認爲你想要的可能是'HAVING'條款。 –

+0

感謝Craig。我添加了錯誤。 – grabury

+0

如果您沒有在聲明中添加「includes」,錯誤是否仍然存在? – lalameat

回答

0

當組你選擇的任何列必須在GROUP_BY或對他們的一些聚集功能。默認情況下,AR拉回所有列,所以你可能要當你得到一個錯誤來限制與.select

相關問題