Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use sessions/cookies in Ruby on Rails without having a user's model or any authentication? [duplicate]

I am creating a quiz game in Rails and would like to create a session to store the current user's data to keep track of the number of questions they answered correctly. All of the tutorials that I've searched for makes one login first then generate a session, can I do this without it?

Edit: Actually I wanted to know if this was possible without having a users model at all?

like image 607
MLZ Avatar asked Apr 20 '16 16:04

MLZ


1 Answers

Yes. The rails session storage mechanism simply links a session id with a session storage (cookie by default).

It basically works like this - when a user first visits your app rails generates a session identifier which is a long hash - the identifier is stored by rails on the server and also sent to the user in a cookie.

In subsequent requests to the app the rails sessions middleware will look at the users cookies for the identifier and if its valid it will unencrypt the session storage cookie and add it to the Rails session. Rails does all this by default without you having to lift a finger.

You can use this session storage for any arbitrary data as long as its within the 4k limit imposed by browsers on cookies. Using some other storage like Redis/Memcached or database storage lets you store more data at the cost of somewhat decreased performance.

The reason you commonly see it connected with authorization is that cookies is kind of the defacto way to link a user id on the server with the current user sitting behind the browser.

  • Rails Guides: Sessions
  • Rails Guides: Rails On Rack if you are interested in how its implemented.
like image 66
max Avatar answered Oct 21 '22 03:10

max