Are you using query caching? That should only be maybe 3 queries tops:
Driver.find # eager include query @car.driver # belongs_to query @driver.car # has_one query
After that, the queries should be repeating and you won't hit the database anymore. Even then, each association call is creating a new ruby object, even if that query is cached.
I have a plugin that enables a simple identity map for ActiveRecord within the context of a controller action: git://activereload.net/active_record_context.git . Every time a record is fetched from the database, it is stored in a global hash by ID. Future requests to receive that record will instead receive the exact same ruby object.
Driver.find 1 # query Driver.find 1 # ID map Driver.find 1 # ID map
The cool thing is you can preload from large queries:
Driver.find :all # query Driver.find 1 # ID map
So, you can select all the drivers and all the cars for those drivers in a single query:
@drivers = Driver.find :all Car.find :all, :conditions => {:driver_id => @drivers.collect(&:id)} @drivers.each do |driver| driver.car # preloaded in the Car.find query end
That's all fine and dandy, but this won't work for has_one associations since the query is by driver_id. The plugin's identity map only indexes records by their primary key. There's a good chance this plugin will be finding its way into the next release of Rails.