# Question About Rails.cache and find method

**URL:** <https://www.ruby-forum.com/t/question-about-rails-cache-and-find-method/154975>\
**Category:** Rails\
**Created:** [December 5, 2008, 6:57pm UTC](https://www.ruby-forum.com/t/question-about-rails-cache-and-find-method/154975 "2008-12-05T18:57:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![johnk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/59ef9b/32.png) [@johnk](https://www.ruby-forum.com/u/johnk)\
**Post date:** [December 5, 2008, 6:57pm UTC](https://www.ruby-forum.com/t/question-about-rails-cache-and-find-method/154975/1 "2008-12-05T18:57:50Z")

</div>

The DB load on my site is getting really high so it is time for me to  
cache common queries that are being called 1000s of times an hour  
where the results are not changing.

So for instance on my city model I do the following:

def self.fetch(id)  
Rails.cache.fetch(“city\_#{id}”) { City.find(id) }  
end

def after\_save; Rails.cache.delete(“city\_#{self.id}”); end;  
def after\_destroy; Rails.cache.delete(“city\_#{self.id}”); end;

So now when I can City.find(1) the first time I hit the DB but the  
next 1000 times I get the result from memory. Great. But most of the  
calls to city are not City.find(1) but @user.city.name where Rails  
does not use the fetch but queries the DB again… which makes sense  
but not exactly what I want it to do.

I can do City.find(@user.city\_id) but that is ugly.

So my question to you guys. What are the smart people doing? What is  
the right way to do this?

I look forward to getting feedback! 🙂

–  
John K.  
removed\_email\_address@domain.invalid

Blog: [http://www.kopanas.com](http://www.kopanas.com)  
Conference: [http://www.cusec.net](http://www.cusec.net)  
Twits: [http://www.twitter.com/kopanas](http://www.twitter.com/kopanas)

---

<div class="post-metadata">

**Author:** ![johnk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/59ef9b/32.png) [@johnk](https://www.ruby-forum.com/u/johnk)\
**Post date:** [December 6, 2008, 3:03pm UTC](https://www.ruby-forum.com/t/question-about-rails-cache-and-find-method/154975/2 "2008-12-06T15:03:45Z")

</div>

On 5 Dec 2008, at 17:57, John K. wrote:

> end
> 
> I can do City.find(@user.city\_id) but that is ugly.
> 
> So my question to you guys. What are the smart people doing? What is  
> the right way to do this?

Live dangerously and override find? 🙂

Fred
