Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一组 Rails 模型记录。是否可以一次性(查询)急切加载所有这些记录的关联?
有时我只有一个数组而不是 AR::Scope。有时我想动态选择稍后要加载的内容。
在 Rails 3 中,可以使用预加载器在现有记录上预先加载关联。
ActiveRecord::Associations::Preloader.new(posts,:comments).run()
在 Rails 4.1+ 中,调用签名略有变化:
ActiveRecord::Associations::Preloader.new.preload(posts,:comments)
好吧,你可以重新找到那些对象。将 ':id' 映射到您的数组上,以获取记录的 id,然后重新查找,这次是急切加载。
Post如果您的模型记录数组是posts,那么它将是:
Post
posts
Post.find(posts.map &:id).includes(:blah)