【问题标题】:how to query active record?如何查询活动记录?
【发布时间】:2021-10-30 12:11:15
【问题描述】:

我想看看我的哪些学生有证书。在学生模型 has_many :certifications 中。当我执行Student.where(company_id:79).countStudent.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 那么是的,它是否返回学生的证书。

【问题讨论】:

  • 你必须使用joinsStudent.where(company_id:79).joins(:certifications)

标签: sql ruby-on-rails ruby activerecord orm


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2013-02-01
    • 2013-04-23
    • 2016-11-10
    • 1970-01-01
    相关资源
    最近更新 更多