Please notice, this is not a question about adding a WHERE condition to an association but a rather advanced question about how to alter the JOIN clause when using eager_load.
Lets say I have these models
class Parent
has_many :children
have_many :grades, through: :children
end
class Child
belongs_to :parent
end
class Grade
belongs_to :child
end
So to eager load the parents I would do:
Parent.eager_load(:grades)
But if I wanted all the parents - but only to eager load the highest scoring like so:
LEFT OUTER JOIN grades ON grades.child_id = children.id AND grades.level = 'A+'
I have tried using includes(:children).joins("LEFT OUTER JOIN grades ON grades.child_id = children.id AND grades.level = 'A+'")
but since Rails does not build the association objects it will cause an extra query for each parent.
I have not found any references on using eager_load
with a custom SQL string and have dug through the source without getting any wiser.