I understand that state can be stored across cookies and the session[]
hash.
Which of the following can be used to store state ACROSS requests from the same user? Select all that apply.
- Cookies
- The
session[]
hash- Instance variables set by a controller method
- Class variables set by a controller method
The answer to this quiz question was (1) and (2). My question is: Why can't (3) and/or (4) store state across requests from the same user?
(3) cannot store state across requests. Every time a request comes into your Rails app, an instance of your controller is created and the appropriate action method is called on it. Once the request has been handled, the controller instance is thrown away and a fresh one is created for the next request.
(4) can technically store state across requests, but the data will be shared across all instances of your controller regardless of which user is making the request. It also cannot be accessed from other controllers, is lost if the server is restarted, and if multiple instances of your Rails app are running at once (quite common in production scenarios), the contents of the class variable will not be shared between them.
Elaboration on why this sort of thing is a bad idea: https://stackoverflow.com/a/1029798/742690
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With