sql - 如何查询活动记录?
问题描述
我想看看我的哪些学生有证书。在学生模型has_many :certifications
中。当我执行Student.where(company_id:79).count
orStudent.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).last
,
x.certifcations
它会返回学生的证书或不返回。
解决方案
由于学生和证书之间存在一对多关联,因此您可以这样做:
Student.where(company_id: 79).joins(:certificates).distinct
推荐阅读
- c# - Oracle 等效于 C# HMACSHA256
- node.js - 使用 npm 安装 express-generator 时出错
- javascript - 仅在激活选项卡时运行事件
- android - 从客户端发送到服务器时文件损坏
- python - django 中一个 CreateView 中的多个 ModelForms
- python - 我应该如何加快pickle.dump()的写入速度
- python - 努力布局我的 Tkinter 应用程序
- c++ - 代码覆盖率 (Lcov) 错误地显示 100% 覆盖率
- wsdl - soapui SOAP 请求为空
- python - Python 安装 - 用户与程序文件夹