Skip to content

Instantly share code, notes, and snippets.

@nitsujw
Created October 22, 2009 19:07

Revisions

  1. nitsujw renamed this gist Oct 22, 2009. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. nitsujw revised this gist Oct 22, 2009. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@ def stats
    @visits = Visit.all
    end

    ## View
    ## View that produces 2 sql hits
    <%= @visits[0] %>
    <% @visits.each do |v| %>
    ...
  3. nitsujw revised this gist Oct 22, 2009. 1 changed file with 6 additions and 2 deletions.
    8 changes: 6 additions & 2 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -5,14 +5,18 @@ def stats

    ## View
    <%= @visits[0] %>
    <%= @visits %>
    <% @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 %>
    <% @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
  4. nitsujw created this gist Oct 22, 2009.
    21 changes: 21 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    ## Controller
    def stats
    @visits = Visit.all
    end

    ## View
    <%= @visits[0] %>
    <%= @visits %>
    #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 %>
    <%= @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]