Active Record query to return records and associations

I’m trying to return a list of records with associations, in SQL it would look something like this*

SELECT grade.id, student.name,
FROM grade 
LEFT OUTER JOIN students 
ON students.id = grades.student_id
WHERE grade.created_at >= '2020-01-01'

Essentially what I’m looking to do is:

grades = Grade.where("created_at >= 2020-01-01")
grades.each {|g| g.student.name}

But in a single query. Unless I’m mistaken, the above would hit the database once to get grades and then repeatedly getting the associated Student record. This is not optimal with my data set which is going to need to query two tables for potentially thousands of records.

I’ve tried several variations using, .select, .includes but I’m only able to return the original record. Eg: Grade.includes(:student).where("grade.created_at >= '2020-01-01') but that only returns Grade records.

*all examples are pseudocode but this is essentially what my query looks like.

I believe includes should work for you. Maybe publish both models here.

Try something like the following… (the name field will be accessible on the grade records):

Grade.select('grades.id, students.name').joins(:students).where('grades.created_at >= ?', date).map{|grade| [grade.id, grade.name]}

1 Like