【发布时间】:2015-10-16 15:54:32
【问题描述】:
我正在使用 Rails 4.2。我有 3 个这样的表:
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
我的目标是选择一些收藏并使用latest_images 关系预加载每个收藏的前 10 张最新卡片。
如果我这样做:
collections = Collection.where(some_condition).includes(:latest_images)
问题是 latest_images 将包含所有卡片,而不仅仅是最后 10 个(即使有 limit(10))
collections.first.latest_images.count # => more than 10!!!
相反,如果我在加载集合后添加limit(10),则会出现 N+1 查询问题:
collections.each { |collection| collection.latest_images.limit(10).do_something } # N+1 QUERY
有什么办法吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 activerecord