无法通过导轨5
问题描述:
我有以下的关联将使用与的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
我该如何解决这个问题?
答
当关联火灾,它会产生像
SELECT students.id, students. ...
FROM students
JOIN schools
ON ...
GROUP BY schools.name
在SQL分组时,一个凸起(SELECT)的SQL查询只能包含的由或聚合分组的列(例如MAX
,MIN
)列(不管它们是否被分组)。因此,添加类似以下内容将变成一个有效的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
学生可以成为许多学校的学生('has_many:schools'),还是他总是一个学生('has_one:school')?甚至没有连接表的“belongs_to:school”? – ulferts