如何编写Rails SQL查询以查找所有子项具有相等值的对象

时间:2017-10-24 10:06:33

标签: sql ruby-on-rails postgresql activerecord relational-algebra

我一直在阅读这篇文章,但无法将其写入Rails范围:

find all parent records where all child records have a given value (but not just some child records)

我有一个CourseSectionQuiz,对象:

class Course < ActiveRecord::Base
  has_many :course_members
  has_many :members, through: :course_members
  has_many :sections
  has_many :quizzes, through: :sections
end

class Quiz < ActiveRecord::Base
  belongs_to :member
  belongs_to :section
end

class Section < ActiveRecord::Base
  belongs_to :course
  has_many :quizzes
end

我想查找某个成员的所有课程,其中与该课程相关的所有测验都具有属性completed = true

所以在我的Member课程中,我最好写一些类似的东西:

has_many :completed_courses, -> { 
   joins(:courses, :quizzes, :sections)
   # .select( 'CASE WHEN quizzes.completed = true then 1 end') ??? maybe ???
}, class_name: 'Course'

哈哈!但除非过于复杂。我一直试图在Course中写这个也没关系。

1 个答案:

答案 0 :(得分:1)

class Member < ActiveRecord::Base
  has_many :courses, through: :course_members
  has_many :course_members

  has_many :completed_courses,
    -> { joins(:quizzes).where.not(quizzes: {completed: [false, nil]}) },
    through: :course_members,
    source: :course
end

如果您的completed布尔列为NOT NULL,请将上面的[false, nil]更改为false

使用示例

irb(main):002:0> Member.first.completed_courses
  Member Load (0.2ms)  SELECT "members".* FROM "members" ORDER BY "members"."id" ASC LIMIT 1
  Course Load (0.1ms)  SELECT "courses".* FROM "courses" INNER JOIN "sections" ON "sections"."course_id" = "courses"."id" INNER JOIN "quizzes" ON "quizzes"."section_id" = "sections"."id" INNER JOIN "course_members" ON "courses"."id" = "course_members"."course_id" WHERE (NOT (("quizzes"."completed" = 'f' OR "quizzes"."completed" IS NULL))) AND "course_members"."member_id" = ?  [["member_id", 1]]