Matthew Leonard
Matthew Leonard

Reputation: 2005

Eager loading the first record of a polymorphic association

I am trying to tune my site to be faster but am having issues tuning an association.

class Post < ActiveRecord::Base
 has_many :photos, as: :annotatable
end

class Photo < ActiveRecord::Base
 belongs_to :annotatable, polymorphic:true
end

I only want to eager load the first photo for each post but am running into syntax errors due to it being polymorphic.

Here is what I have tried:

  has_many :primary_photo, as: :annotable, -> { order('photos.sort_order ASC').limit(1) }, class_name: 'Photo'

The error I get when I try the above is:

syntax error, unexpected ',', expecting => ...r('sort_order ASC').limit(1) }, class_name: 'Photo' ... ^

And then: Post.includes(:primary_photo)

Any ideas on how to make this work?

Upvotes: 1

Views: 64

Answers (1)

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14412

The method signature expects the options to go after the scope. Try it like this:

has_many :primary_photo, -> { order('photos.sort_order ASC').limit(1) }, class_name: 'Photo', as: :annotable

Upvotes: 1

Related Questions