0

我有以下的關聯將使用與的has_many組:無法通過導軌5

class Student < ApplicationRecord 
    has_many :people_schools 
    has_many :schools, through: :people_schools 
end 

class PeopleSchool < ApplicationRecord 
    belongs_to :student 
    belongs_to :school 
end 

class School < ApplicationRecord 
    has_many :people_schools 
    has_many :students, through: :people_schools 
end 

我試圖讓他們通過學校組織的學生名單。我曾嘗試以下:

Student.joins(:schools).all.group('schools.name') 

,但我得到了以下錯誤:

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "students.id" must appear in the GROUP BY clause or be used in an aggregate function 

我該如何解決這個問題?

+0

學生可以成爲許多學校的學生('has_many:schools'),還是他總是一個學生('has_one:school')?甚至沒有連接表的「belongs_to:school」? – ulferts

回答

0

當關聯火災,它會產生像

SELECT students.id, students. ... 
FROM students 
JOIN schools 
ON ... 
GROUP BY schools.name 

在SQL分組時,一個凸起(SELECT)的SQL查詢只能包含的由或聚合分組的列(例如MAXMIN)列(不管它們是否被分組)。因此,添加類似以下內容將變成一個有效的SQL:

# column that is grouped by 
Student.joins(:schools).group('schools.name').select('schools.name') 
# aggregate function 
Student.joins(:schools).group('schools.name').select('schools.name, COUNT(students.id)') 

但是如何你要修復它在你的情況下,取決於你想要得到的查詢是什麼。

在回答評論

假設一個學生只有一個學校,這需要改變聯想到belongs_to :school的成員(不包括聯接表)或has_one :school(帶連接表)。

Student.includes(:school).group_by(&:school) 

這將發出一條SQL語句讓所有學生和他們的學校(急於加載優化)。只有在模型(學生,學校)實例化紅寶石對象之後,纔會評估該方法,該方法將返回一個散列,其中學校是引用學生數組的關鍵。

+0

有12所學校。我試圖獲得12個數組的數組。在這12個陣列中,每個都是學校的學生。我已經使用group_by來做到這一點,沒有has_many通過之前。 – Philip7899