Search code examples
ruby-on-railsetaghttp-cachingruby-on-rails-6

Rails fresh_when should include current user id in etag


I see many examples like this:

def show
  @article = Article.find(params[:id])
  fresh_when(@article)
end

However the page also contains information (like top navigation) about the logged in user. A user can:

  • log in as user A
  • visit the article
  • log out
  • log in as user B
  • visit the article again

... Oops the user will see data about user A, instead of user B, because the article was not modified.

How can I include the current user id in the hash (etag)? Or, are there any other solutions to avoid the issue described above?


Solution

  • Maybe you can add the current_user id to the etag in all of your controllers.

    class ApplicationController < ActionController::Base
      etag { current_user.try :id }
    end
    

    This way, you can solve the problem with the logged-in user who might get different content than a non-logged-in user.