Ruby on Rails
HowtoWorkWithSessions
Sessions in 30 seconds
Setting a session value:
session[:greeting] = "Hello world!"
Reading a session value:
session[:greeting] # => "Hello world!"
Deleting a single session value:
session[:greeting] = nil
Completely removing a previously-set key/value pair:
[not possible]
Clearing an entire session:
reset_session
Gotchas with sessions
- Strange application errors – If you put something dodgy into the session (e.g. an unaccessible object) then whichever webserver you running may refuse to run the main dispatcher. Removing all session data should fix it. See TipsAndTricks for session deletion information
A more in depth explanation available at HowtoAvoidSessionRestoreError
- Items added to Session hash not retained – Your browser must be configured to accept cookies from the server. Sounds stupid and obvious but I wasted one whole day wondering why data that I put in the hash in one method wasn’t available in another.
There can be a possible workaround IF
- lot of session variables going to be used and we worry about the amount of resources going to be allocated
- we like our session information to be easy to read, manage and debug
- we need more control over session variables we created
- have your variables inside a session variable hash, as far as I know we cannot delete the created session variable, but the items inside our variable can be maniupulated the way we like to do so
- add, modify, delete those items inside the session variable… keeping your session variables clean and more meanigfull than ending up with lot of unwanted session variables in case we create randomly named key/value pairs for some reason
- this is just a workaround when we need to have variables in our session and also need to have more control over them
More information
- sessions — explains the basics of sessions in Rails
See also
Questions/Noob remarks
gave
You have a nil object when you didn't expect it !
...
occured while evaluating nil.[]=
Um. What are you even doing using the constructor anyway? Surely before_filter is the way.