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) }
enddef 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?