I have the following imaginary class
class A < ActiveRecord::Base
has_many :objects, -> { order(:created_at) }, class_name: 'B'
has_one :last_object, -> { order(created_at: :desc).limit(1) }, class_name: 'B'
scope :with_last_object, -> { includes(:last_object) }
end
I added a second association to model A and the scope to avoid N+1 request in the next case:A.all.map(&:last_object)
. So I write A.all.with_last_object.map(&:last_object)
.
But it fails: it retrieve only 1 last_object
for all instances of A. From Postgres Logs
SELECT "b".* FROM "b" WHERE "b"."a_id" IN (1, 2, 3, ...) ORDER BY "b"."created_at" DESC LIMIT $1
Is there a way to avoid N+1 issue in this situation?
limit(1)
on ahas_one
,has_one
already limits for you.b
relation which might take much timelimit(1)
does nothing here, from a performance standpoint.