Rails fragment caching with personalization

189 views Asked by At

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.

1

There are 1 answers

1
miler350 On

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?