In ActiveRecord we can get the first row of a table that is not part of some related criteria.

In this example we are going to retrieve the next course where a student has yet to receive a grade. If we were to omit the .first(), we could get all the courses.

This query operates on the assumption we have a method .get_grades() which takes a parameter of the model and returns all the grades for that model.

The model diagram looks like this:

Student - has_many -> Grades - belong_to -> Courses
Course.where('id not in (?)', Student.find(3245).get_grades(Course).map(&:id)).first


Leave a Reply

Your email address will not be published. Required fields are marked *