title: ActiveRecord find associated records of associated records in one query
body: <p>I'm trying to find an ActiveRecord and/or SQL way to only use 1 query for the following</p>
  
  <p><strong>Get all chapters written by an author given that an author has_many books and a book has_many chapters</strong></p>
  
  <pre><code>class Author &lt; ActiveRecord::Base
    has_many :books
  end
  
  class Book &lt; ActiveRecord::Base
    belongs_to :author
    has_many :chapters
  end
  
  class Chapter &lt; ActiveRecord::Base
    belongs_to :book
  end
  </code></pre>
  
  <p>This works but it uses two queries</p>
  
  <pre><code>Chapter.where(book_id: author.books.map(&amp;:id))
  
  Book Load (0.4ms)  SELECT `books`.* FROM `books`  WHERE `books`.`author_id` = 1
  Chapter Load (0.4ms)  SELECT `chapters`.* FROM `chapters`  WHERE `chapters`.`book_id` IN (1, 2, 3)
  </code></pre>
  
  <p>This works but it returns an array object not an ActiveRecord relation object</p>
  
  <pre><code>author.books.map(&amp;:chapters)
  </code></pre>