Includes
suggest changeincludes 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents