Includes

suggest change

includes loads the named associations in as few queries as it can. A where on books also filters the authors, and Rails turns that includes into a join (eager_load). That filter does not reliably limit author.books to bestsellers. Scope the association if the in-memory collection should contain only those books.

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

@authors.each do |author|
  author.books.each do |book|
    puts book.title
  end
end

Author.joins(:books).where(books: { bestseller: true }) loads matching authors and does not preload books. Use joins when you do not need the associated records.

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

# prints names without another query
@authors.each { |author| puts author.name }

# loads books with a query per author
@authors.each do |author|
  author.books.each do |book|
    puts book.title
  end
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents