首页 > 解决方案 > 如何查询活动记录?

问题描述

我想看看我的哪些学生有证书。在学生模型has_many :certifications中。当我执行Student.where(company_id:79).countorStudent.where(company_id:79).all查询时,它会返回学生人数(748 人)和所有学生的数组。但是,我只能咨询是否有证书,每个学生一份一份。当我这样做时Student.where(company_id:79).certifications,它会返回一个错误:(undefined method "certifications" for #<Student::ActiveRecord_Relation:0x0000564640516fd0>)

当我这样做时x = Student.where(company_id:79).lastx.certifcations它会返回学生的证书或不返回。

标签: sqlruby-on-railsrubyactiverecordorm

解决方案


由于学生和证书之间存在一对多关联,因此您可以这样做: Student.where(company_id: 79).joins(:certificates).distinct


推荐阅读