I'm using Rails 4.2. I have 3 tables like this:
class Collection < ActiveRecord::Base
has_many :shares
has_many :images, through: :shares
has_many :latest_images, -> { order(created_at: :desc).limit(10) }, class_name: 'Image', through: :shares, source: :image
end
class Share < ActiveRecord::Base
belongs_to :image
belongs_to :collection
end
class Image < ActiveRecord::Base
has_many :shares
has_many :collections, through: :shares
end
My goal is to select some collections and preload the first 10 newest cards of each collection using the latest_images
relation.
If I do simply:
collections = Collection.where(some_condition).includes(:latest_images)
The problem is latest_images will contain all cards, not only the last 10 (even if there's a limit(10)
)
collections.first.latest_images.count # => more than 10!!!
Instead, if I add the limit(10)
after loading the collections, I'll have a N+1 query problem:
collections.each { |collection| collection.latest_images.limit(10).do_something } # N+1 QUERY
Any solution?