Object caching

Does Rails cache all objects that are accessed during a request?

If one object is accessed several times during a request, would its value be read from memory, or fetched from the database over and over again?

I'm sure that objects that were passed by the controller, like @something would be cached, because their reference is passed, but what about other objects which might be deleted by the garbage collection?

So, if I plan to display the same object over and over again within a partial, for the same call, how do I make sure it's not fetched from the database on every render?

Thanks, Amir

You can pre-fetch the data in the controller. If it is an associated model, you can use find()'s :include to fetch it in one sql call. http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M000992

helzer wrote:

Hi,

model, you can use find()'s :include to fetch it in one sql call. ActiveRecord::Base

Does Rails cache all objects that are accessed during a request

Also... ActiveRecord will keep a pretty simple (but somehow effective) cache on a per-model basis. The last query result for each model is cached, and if you are trying to execute the same query, then it will be coming directly from memory. Take into account there is only a cached resultset per model.

You can play a bit with that to see how it works by opening a console in development mode and executing some finds as you are tailing the log. You'll see when you repeat the same find against a model, no new query is launched againts the db.

If I'm not mistaken, rails 2 will improve the AR cache, but so far that's the way it works.

regards,

javier ramirez

Hi again,

Sorry about that, but my prior email was completely messed up. I really don't know how i got the idea of a per-model last query cache (maybe an old rails version? not sure of that), but truth is AR doesn't cache like that.

There is a cache for the associations, so if you have a variable with a, for example, has_many and you call on the association, only the first time you use it is the query to be launched.

Sorry once again about the misleading,

javier

Actually, Active Record on edge rails does some caching for DB queries. It's nothing sophisticated, but it helps out a lot. I wrote an article comparing the different approaches in AR that you can use (piggy backing, eager includes, query caching, and an object caching approach in a plugin I wrote)

http://activereload.net/2007/5/23/spend-less-time-in-the-database-and-more-time-outdoors

Hi Rick,

Your plugin is great. So, I guess when Rails 2 comes out, I should probably stop using it, as it's already integrated, right?

Thanks, Amir