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?
Asked
Active
Viewed 197 times
2 Answers
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
-
Does this mean `record_visit` would be called before any function in the controller gets called? – Biju Dec 08 '18 at 06:28
-
@Biju correct. Here's the documentation https://guides.rubyonrails.org/action_controller_overview.html#filters – Alex Suslyakov Dec 09 '18 at 16:31