包括

帶有 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