# Caching a has\_many child's parent.

**URL:** <https://discuss.rubyonrails.org/t/caching-a-has-many-childs-parent/24092>\
**Category:** rubyonrails-talk\
**Created:** [January 30, 2008, 6:54pm UTC](https://discuss.rubyonrails.org/t/caching-a-has-many-childs-parent/24092 "2008-01-30T18:54:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rick\_Olson](https://avatars.discourse-cdn.com/v4/letter/r/898d66/32.png) [@Rick\_Olson](https://discuss.rubyonrails.org/u/Rick_Olson)\
**Post date:** [January 30, 2008, 6:54pm UTC](https://discuss.rubyonrails.org/t/caching-a-has-many-childs-parent/24092/1 "2008-01-30T18:54:52Z")

</div>

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| &nbsp;&nbsp;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.

---

<div class="post-metadata">

**Author:** ![Steve\_Ross](https://avatars.discourse-cdn.com/v4/letter/s/3d9bf3/32.png) [@Steve\_Ross](https://discuss.rubyonrails.org/u/Steve_Ross)\
**Post date:** [January 30, 2008, 7:32pm UTC](https://discuss.rubyonrails.org/t/caching-a-has-many-childs-parent/24092/2 "2008-01-30T19:32:19Z")

</div>

Rick, thanks for this explanation. I'm wondering whether the OP's question was more related to the use case:

- I have a Driver - Who has a car - And I want to know what drivers also have that car - And I want to know all the cars all of those drivers have

Driver.find(:first).car.drivers.cars

Question to OP: Was this actually what you had in mind or did I misread?
