1

My site has a top navigation menu bar which has infrequently changed contents and it's therefore a good candidate for fragment caching. But if a user is signed in, part of the menu bar will have the user's name in it, and is therefore personalised and can't be cached.

I can either:

  1. Fragment cache the static part and serve up the personalised part separately. That seems pretty easy.

  2. Cache the lot, possibly in memcached or CloudFront, keep the user's name in the session, and use JavaScript to extract the user's name from the session and personalise the page at the client end.

What is the best option to go with? Preferably based on personal experience of similar situations.

John Small
  • 942
  • 2
  • 12
  • 21

1 Answers1

0

Try this:

  ##in user.rb to cache user

 after_save :invalidate_cache

  def self.serialize_from_session(key, salt)
    single_key = key.is_a?(Array) ? key.first : key
    Rails.cache.fetch("user:#{single_key}") do
      User.where(:id => single_key).entries.first
    end
  end


  def invalidate_cache
    Rails.cache.delete("user:#{id}")
  end

Credit: Rails Devise: How do I (mem)cache devise's database requests for the user object?

Community
  • 1
  • 1
miler350
  • 1,411
  • 11
  • 15
  • Thanks, that solves part of the problem, hitting the db with 'select * from user where etc' on every page request that requires a current user. But it doesn't solve the problem of having a mostly static page, with a small part of it that's personalised to the logged in user. – John Small Dec 16 '14 at 12:52