I'm currently working on performance optimization for a forum app.
I've noticed in the logs that some queries are being run over and over
again with each page request.
I believe, and the logs support, that ActiveRecord caches the objects
referenced by belongs_to, has_one, has_many, and
However, what about ActiveRecords and arrays of ActiveRecords that don't
fall into that category, objects and arrays of objects that are
calculated or derived in other method calls? Can they be cached
Things I've tried:
- storing the objects in the Session. I get marshaling problems when
the session is saved.
- sorting the object ids in the Session. Still have to make a database
call, Post.find(session[:some_id]), *every* time I use the stored id.
- converting these methods to has_one or has_many relationships. Can't
figure out how to get :conditions that can reference attributes of the
Things I don't want to jump to yet:
Surely, there is some simple mechanism I have overlooked!
If you just stroe the id in the sessions then you can write a method that will let you call that object multiple times per request with only one call to the database. The typical example is current_user:
@current_user ||= session[:user_id] ? User.find_by_id(session[:user_id]) : nil
-- Ezra Zygmuntowicz-- Lead Rails Evangelist
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)