Back to Course

Practice · Scaling · Card 2

Count the queries this view runs

A simple index view. 50 posts. Each line shows the post title and the author name. How many SQL queries actually fire?

The code

A controller and the view it renders. Post belongs_to :user. No preloading is set up.

# app/controllers/posts_controller.rb
def index
  @posts = Post.order(created_at: :desc).limit(50)
end

# app/views/posts/index.html.erb
<% @posts.each do |post| %>
  <p>
    <%= post.title %>
    by <%= post.user.name %>
  </p>
<% end %>

The question

From the moment @posts is touched in the view until the view finishes rendering, how many SQL queries does Rails send to the database?

Take a moment. Pick the best answer. Wrong picks reveal why they're wrong, which is half the point.