Loading ActiveRecords only once per page

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
has_and_belongs_to_many.

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
somewhere?

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
    current instance.

Things I don’t want to jump to yet:

  • memcached

Surely, there is some simple mechanism I have overlooked!

Hi~

On Jan 31, 2007, at 1:11 PM, Robert H. wrote:

However, what about ActiveRecords and arrays of ActiveRecords that
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
    current instance.

Things I don’t want to jump to yet:

  • memcached

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:

def current_user
@current_user ||= session[:user_id] ? User.find_by_id(session
[:user_id]) : nil
end

HTH

– Ezra Z.
– Lead Rails Evangelist
[email protected]
– Engine Y., Serious Rails Hosting
– (866) 518-YARD (9273)

Ezra Z. wrote:

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:

def current_user
@current_user ||= session[:user_id] ? User.find_by_id(session
[:user_id]) : nil
end

HTH

– Ezra Z.

Thanks! I should have put that in the list of things I’ve already tried
(got marshaling problems when saving the object), but I’m definitely
going to give it another go.

Cheers,
rob

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs