【发布时间】:2011-12-17 20:30:35
【问题描述】:
在 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 for rails 中看到的渴望加载是 ActiveRecord::Associations 的任何扩展上的类方法,问题是说你没有使用类方法的能力,所以你需要使用某种实例方法
我认为它看起来像的代码示例类似于
post = Posts.find(:all)
posts.get_all(:comments) # runs the query to build comments into each post without the class method.
【问题讨论】:
标签: ruby-on-rails activerecord lazy-loading eager-loading