Skip to content

Instantly share code, notes, and snippets.

@nitsujw
Created October 22, 2009 19:07
Show Gist options
  • Save nitsujw/216192 to your computer and use it in GitHub Desktop.
Save nitsujw/216192 to your computer and use it in GitHub Desktop.
## Controller
def stats
@visits = Visit.all
end
## View that produces 2 sql hits
<%= @visits[0] %>
<% @visits.each do |v| %>
...
<% end %>
#produces 2 sql hits
(0.000052) SELECT `id`, `user_id`, `created_at`, `updated_at` FROM `visits` WHERE `created_at` > '2009-10-15 00:00:00' ORDER BY `created_at` DESC LIMIT 1
(0.000036) SELECT `id`, `user_id`, `created_at`, `updated_at` FROM `visits` WHERE `created_at` > '2009-10-15 00:00:00' ORDER BY `created_at` DESC
## View that produces 1 sql hit
<% @visits.each do |v| %>
...
<% end %>
<%= @visits[0] %>
#produces
(0.000036) SELECT `id`, `user_id`, `created_at`, `updated_at` FROM `visits` WHERE `created_at` > '2009-10-15 00:00:00' ORDER BY `created_at` DESC
If you don't call @visits first it forces a separate query for @visits[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment