Me
About
Gallery
Company
Girl


Projects
Ruby on Rails
Basecamp
Highrise
Backpack
Campfire
Ta-da List
Writeboard


More
Feed
Archives

October 23, 2:21

Beating the n+1 problem with Active Record

Sean is yet another Java programmer burning the midnight oil with Ruby on Rails. Among many kind words, he offers a simple example on how to beat the dreaded 1+1 problem that a naive ORM will kill performance on any iterations with.

However, that doesn't solve the 1+1/iteration problem because this will face the same issue. But the solution is much simpler and elegant. I modify the Account class to:
class Account < ActiveRecord::Base
  has_one :owner
 
  def self.find_with_owner
    find_all(
      'select a.*, o.first_name, o.last_name ' +
      'from account a and owner o ' +
      'where a.owner_id = o.owner_id'
    )
  end
end

Welcome on board, Sean. I hope the productivity gains you've experience will allow that midnight oil to be replaced with a day-time engagement.

P.S.: There's an expanded discussion of this piggy-back technique on the Active Record wiki.