繁体   English   中英

渴望在Rails中的ActiveModel实例上加载关联

[英]Eager loading associations on ActiveModel instances in Rails

在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

但是,如果您无法访问类方法,并且只能访问实例方法的集合,那该怎么办呢?

然后你就陷入了查询密集型延迟加载。

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

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


因此,对于我在rdoc中看到的对于rails的热切加载是对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)

我想我得到了你所要求的。

但是,我认为您不必担心您可以访问哪些方法。 外键关系(以及ActiveRecord关联,例如has_manybelongs_to等)将负责确定如何加载相关记录。

如果您可以提供您认为应该发生的具体示例,以及无效的实际代码,那么您将更容易看到您所获得的内容。

您如何获得模型实例的集合,以及您使用的是哪个版本的Rails?

您是说您完全无法访问控制器或模型本身?

给你最好的答案取决于知道这些事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM