Consider a Rails application with the following two models: Book and Video. Book has properties title and summary. Video has properties title and studio. Suppose that when both of these models are displayed in a the application, a user may add a Comment (with single property body). (E.g. both Books and Videos have many Comments).
Create the appropriate migrations and models (including relationships).
Now, suppose on your home page you want to show a list of all recent Comments, sorted by created_at. The list should show the body of the Comment as well as the type and title of the object about which the comment was made.
Write the ActiveRecord query necessary to display this list of recent Comments. Explain what the N + 1 query problem is, and how you've avoided it in your solution.