包括

带有 includes 的 ActiveRecord 确保使用尽可能少的查询加载所有指定的关联。因此,当使用关联表查询表中的数据时,两个表都会加载到内存中。

@authors = Author.includes(:books).where(books: { bestseller: true } )

# this will print  results without additional db hitting
@authors.each do |author| 
  author.books.each do |book|
    puts book.title
  end
end

Author.joins(:books).where(books: { bestseller: true } ) 只会将具有条件的作者加载到内存中而不加载书籍。当不需要有关嵌套关联的其他信息时,请使用 joins

@authors = Author.joins(:books).where(books: { bestseller: true } )

# this will print results without additional queries
@authors.each { |author| puts author.name }

# this will print results with additional db queries
@authors.each do |author| 
  author.books.each do |book|
    puts book.title
  end
end