3

I would like to check if a controller is being called for the very first time in the user's session. Is a class variable the right choice for this? Any good practice as to how to implement this check?

Biju
  • 820
  • 1
  • 11
  • 34

2 Answers2

3

You can use session variable that sets info in user session. For instance:

if session[:my_controller_accessed]
  do_stuff_for_another_visit
else
  session[:my_controller_accessed] = true
  do_stuff_for_first_visit
end

More on sessions: https://www.justinweiss.com/articles/how-rails-sessions-work/

mrzasa
  • 22,895
  • 11
  • 56
  • 94
3

The answer is in your question: In a user session

You can do smth like this in your controller

before_action :record_visit

# ...


def record_visit
  session[:visited_controllets] ||= {}
  session[:visited_controllets][self.class.name] = true
end

Later you can check whether the given controller was accessed using session[:visited_controllets][contoller_class_name]

Alex Suslyakov
  • 2,042
  • 2
  • 14
  • 15