1

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?

3
  • 1
    you shouldn't have a limit(1) on a has_one, has_one already limits for you.
    – user229044
    Commented Mar 11, 2019 at 15:52
  • yes, but in that case, it makes a request on all b relation which might take much time
    – Gleb
    Commented Mar 11, 2019 at 16:42
  • No, limit(1) does nothing here, from a performance standpoint.
    – user229044
    Commented Mar 11, 2019 at 18:19

2 Answers 2

1

The problem comes from your definition of the last_object, which active record is not able to convert into an eager load.

Either you play hard with self-joins, so you can have some tricky (and possibly underperforming) SQL like

SELECT  "b".* FROM "b"
JOIN "b" AS "b_from_same_a"
  ON "b"."a_id" = "b_from_same_a"."id"
WHERE "b"."created_at" = MAX("b_from_same_a"."created_at")
GROUP BY "b".*

or you can explicitly track the last one:

class B < ActiveRecord::Base
  after_save :set_last, on: :create

  def set_last
    self.class.where(a_id: a_id).update_all(last: false)
    self.update_column(last: true)
  end
end

and modify your association scopes accordingly.

1
  • Only concern with option 2 is deletion of the "last" record. Would certainly need a destruction hook as well Commented Mar 12, 2019 at 16:13
0

I ended with this (thanks to my colleague)

has_one :last_object, -> {
    from(
      <<~SQL
        (select * from
          (select
              *,
              row_number() over(partition by b.a_id order by b.created_at desc) as rn
          from
              b) as inner_b
        where rn = 1) as b
      SQL
    )
  }, class_name: 'B', dependent: :delete

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.