ruby-on-rails - Rails中ActiveModel实例上的热切加载关联

标签 ruby-on-rails activerecord lazy-loading eager-loading

在RoR中,对于新手来说,加载类和类似的习俗是一个很常见的错误#

# The bellow generates an insane amount of queries
# post has many comments
# If you have 10 posts with 5 comments each
# this will run 11 queries 
posts = Post.find(:all)
posts.each do |post|
  post.comments
end


该解决方案非常容易加载

# should be 2 queries
# no matter how many posts you have
posts = Post.find(:all, :include => :comments) # runs a query to get all the comments for all the posts
posts.each do |post|
  post.comments # runs a query to get the comments for that post
end


但是,如果您无权访问类方法,而仅有权访问实例方法的集合,该怎么办?

然后,您将陷入查询密集型延迟加载中。

有没有一种方法可以最小化查询以从实例集合中获取comments集合的所有posts

答案的补充(也添加到上面的代码中)



因此,要从我在railc的rdoc中看到的渴望加载的是ActiveRecord :: Associations的任何扩展上的类方法,问题是说您没有能力使用类方法,因此您需要使用某种实例方法

我认为看起来像的代码示例是

post = Posts.find(:all)
posts.get_all(:comments) # runs the query to build comments into each post without the class method.

最佳答案

在Rails 3.0和更低版本中,您可以执行以下操作:

Post.send :preload_associations, posts, :comments


您可以传递关联名称的数组或哈希,例如可以包含以下内容:

Post.send :preload_associations, posts, :comments => :users


在Rails 3.1中,它已被移动,您可以这样使用Preloader

ActiveRecord::Associations::Preloader.new(posts, :comments).run()


从Rails 4开始,其调用已更改为:

ActiveRecord::Associations::Preloader.new.preload(posts, :comments)

关于ruby-on-rails - Rails中ActiveModel实例上的热切加载关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8547722/

相关文章:

ruby-on-rails - 如何设置自定义 y 轴 Chartkick

ruby-on-rails - 具有绑定(bind)变量和可选参数的条件

java - @RefreshScope 可以渴望吗

javascript - 如何使用 oclazyload 加载的外部模块加载 Angular 翻译?

c# - 延迟加载不调用函数

ruby-on-rails - 设计生成 View

ruby-on-rails - Rails - 如何在编辑模式下渲染嵌套表单部分

ruby-on-rails - 如何将多个参数传递给 backgroundrb 的一名 worker

php - CodeIgniter 事件记录查询仅返回表中的第一个条目

ruby-on-rails - Rails 3 - 通过关联进行 has_many 的 where 子句