girbic
girbic

Reputation: 321

Is session a method or hash in Rails? Slightly confused

Got a really simple question. I'm doing the railstutorial by Michael Hartl and it talks about using the session method:

Logging a user in is simple with the help of the session method defined by Rails... We can treat session as if it were a hash, and assign to it as follows:

session[:user_id] = user.id

It says you can treat session as if it were a hash, but I'm confused because it is called the session method, so is anything actually being called? My guess is that by inserting into the session hash, there is a session function that looks into the hash to see if there is anything present? I'm not really sure how it works.

Upvotes: 8

Views: 2077

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Would be rude not to mention the Session documentation:

All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).

Basically, each time someone visits your Rails app, it will create a small cookie in their browser, identifiable by a unique ID (not user ID).

This cookie is essentially a Ruby hash, hence why you can store hashed data inside it:

session[:your_hash] = "TEST"

This will allow you to store small snippets of data (such as user_id or others) through requests.


The main reason Rails has this is down to HTTP being a stateless protocol.

Stateless protocols are contrary to stateful protocols; they don't retain the state between requests, thus you have to reinvoke data, etc, each time a new instance of the application is accessed.

Simply, this translates into Rails being a "dumb" system - only remembering data you send it each request. Session variables have been used by developers for decades to provide base information about users / preferences etc, allowing you to "rebuild" a user with each request.

This is why you have to save the user_id as a session - each time you wish to reference a logged-in user's data, it has to be built from that id stored in the sessions hash.

Upvotes: 4

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

It is a method that returns an object which supports (some of) the same methods a Hash object supports, such as [] and []=. Actually, it is an ActionDispatch::Request::Session object.

Upvotes: 3

Related Questions