2016-06-13 35 views
0

我想對我的Rails模型執行group_by操作,但似乎存在一些問題。我有一個名爲學生模型無法在Rails活動記錄中執行組操作

class CreateStudents < ActiveRecord::Migration 
    def change 
    create_table :students do |t| 
     t.integer :student_id 
     t.string :department 
     t.integer :maths 
     t.integer :physics 
     t.integer :chemistry 
     t.string :year 

     t.timestamps null: false 
    end 
    end 
end 

on Rails的控制檯,當我運行

s = Student.all.group("date(created_at)") 

我有以下錯誤:

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "students.id" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: SELECT "students".* FROM "students" GROUP BY date(created_at... 
      ^
: SELECT "students".* FROM "students" GROUP BY date(created_at) 

然而,當我運行

s = Student.all.group("date(created_at)").count 

它成功運行。

我是一個新的鐵路。

的Rails 4.2.6 的Ruby 2.3.1

+0

可能重複的[鏈接](http://stackoverflow.com/questions/18061285/postgresql-must-appear-in-the-group-by-clause-or-be -used-an-aggregate-functi) –

回答

0

你有什麼期望是group結果沒有count

假設你有一個表:

id | created_at 
——————|——————————— 
    1 | 2016-06-12 
    2 | 2016-06-12 
    3 | 2016-06-12 
    4 | 2016-06-13 
    5 | 2016-06-13 
count

現在的結果將是:(第一列的值是不確定的)

count | created_at 
——————|——————————— 
    3 | 2016-06-12 
    2 | 2016-06-13 

但是,如果沒有count有衝突

這個問題與Rails無關,這是一個典型的SQL問題,沒有良好的聚合。請分享,你其實是想實現(接受,因爲這操作的結果。)

無論你想組在Ruby端結果,得到陣列和組它與紅寶石Enumerable#group_by,陣列上實例(請注意,這是相當低效):

Model.all.group_by &:created_at 
+0

我想要所有按'created_at'分組的字段。如果我錯了,請告訴我如何做到這一點。 我想要所有同學的平均分數student_id – aks

+0

你是什麼意思「所有的領域」?鑑於我提供的非常簡單的輸入數據,期望的結果是什麼? – mudasobwa

+0

我想要每個學生的student_id的平均分數,我可以這樣做嗎? – aks

0

使用此代碼:

s = Student.group(:created_at) 

如果你想使用group而不是group_by,則不要使用all,因爲它返回對象數組。

使用group_by

s = Student.all.group_by(&:created_at) 
+0

由於我在我的回答中描述的原因,前者會產生相同的錯誤,後者是ruby/client端的數組_grouping_。 – mudasobwa

+0

我已經更新了我的答案。 –

相關問題