Ruby on rails Rails:`includes`a`与`limit`有很多关系`
我使用的是Rails 4.2。我有3张这样的桌子:Ruby on rails Rails:`includes`a`与`limit`有很多关系`,ruby-on-rails,ruby-on-rails-4,activerecord,Ruby On Rails,Ruby On Rails 4,Activerecord,我使用的是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: :
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
问题是最新的\u图像将包含所有卡片,而不仅仅是最后10张(即使有限制(10)
)
相反,如果在加载集合后添加限制(10)
,则会出现N+1查询问题:
collections.each { |collection| collection.latest_images.limit(10).do_something } # N+1 QUERY
有什么解决办法吗?在“急切加载关联”下面有一个注释: 如果使用指定的:limit选项加载关联,将忽略该关联,并返回所有关联对象 因此,尽管这可能不是直观的行为,但它的行为是有记录的
解决方法是不要急于加载有限的相关文件,然后单独访问。正如您所指出的那样,这并不理想,但几乎可以肯定的是,加载所有关联对象时不受限制是可取的。因此,没有办法在不加载所有内容的情况下立即加载数据并避免N+1查询?不,我不认为不使用arel接口。我想你可以编写自己的代码来完成它,但不幸的是,你不会免费得到它。
collections.first.latest_images.count # => more than 10!!!
collections.each { |collection| collection.latest_images.limit(10).do_something } # N+1 QUERY