Trip
Trip

Reputation: 27114

How to write a Rails SQL query for finding an object where all children have an equal value

I've been reading this, but can't make sense of writing it into a Rails scope :

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

I have a Course, Section, and Quiz, object :

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

I'd like to find all courses of a member, where all quizzes related to that course have the attribute completed = true.

So in my Member class, I'd ideally like to write something like :

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

Haha! But barring that being too complicated. I've been trying to write this simply in the Course would also be fine.

Upvotes: 1

Views: 443

Answers (1)

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

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

If your completed boolean column is NOT NULL, then change [false, nil] above to just simply false

Usage Example

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]]

Upvotes: 2

Related Questions