< Return to Blog

Rails' ActiveRecord::Explain in Action!

Note: the following partial is not DRY; it's functional which is what's important for now — I'll refactor bits like this at a later point.

I was chatting with my friend Jon-Paul Lussier (@jonpaullussier) and I ended up nicking the new Panel UI 'widget' (it's just pure CSS) from ZURB's Foundation and ended up refactoring one my blog's partials — the one that presents the 3-column block on the landing page.

Wanted to pass an array instead of a direct string and just wanted to ensure the SQL query made sense

From: /Users/mdesilva/code/linode.mwdesilva.com/rails/mwdesilva.com/app/views/posts/_featured.html.erb @ line 2 in ActionView::CompiledTemplates#_app_views_posts__featured_html_erb__1174825261695298304_70309845808520:

    1: <% query = Post.published.joins(:tags).where(:tags => {:name => @feature_tags}).order('published_at DESC') %>
 => 2: <% binding.pry %>
    3: <% unless query.empty? %>
    4:   <% query.order('id DESC').limit(@latest_post.tags.where(:name => @feature_tags).empty? ? 3 : 4).reject{|r| r == @latest_post }.each do |p| %>
    5:     <h4><%= link_to "#{p.title}", post_path(p) %></h4>
    6:     <% unless p.post_image.to_s == "/post_images/original/missing.png" %>
    7:       <br/>

=> ["Lifestyle", "Reviews"]4271688>>)> @feature_tags = ["Lifestyle","Reviews"] [2] pry(#<#<Class:0x007fe494271688>>)> @latest_post.tags.where(:name => @feature_tags).explain
=> "EXPLAIN for: SELECT \"tags\".* FROM \"tags\" INNER JOIN \"post_taggings\" ON \"tags\".\"id\" = \"post_taggings\".\"tag_id\" WHERE \"post_taggings\".\"post_id\" = 29 AND \"tags\".\"name\" IN ('Lifestyle', 'Reviews')\n0|0|1|SEARCH TABLE post_taggings USING INDEX index_post_taggings_on_post_id (post_id=?) (~10 rows)\n0|1|0|SEARCH TABLE tags USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)\n0|0|0|EXECUTE LIST SUBQUERY 1\n"

It's an utterly fantastic addition to Rails!