在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/