Nox
Nox

Reputation: 246

Session misunderstanding in Ruby on Rails

I'm working under rails and, as a beginner, I am trying to understand how the session feature works. I put my sessions under active record, but when I do this:

    @request = Facebook::Request.parse_signed_request(params[:signed_request],
    Settings.facebook.app_secret) 
    puts session
    @admin = Admin.find_by_fb_userid(@request["user_id"])
    session[@request["user_id"]] = @admin ? @admin : nil

My session continue to display:

{}

Thanks for your help !

Upvotes: 1

Views: 341

Answers (3)

Nox
Nox

Reputation: 246

Ok my fault was that I was working on a facebook app I guess and for every refresh, the session is reset by the peer.

But when I continued in my process, everything instantly worked.

And even if session is a stateless protocol, it is used, through the storage that is used to keep the session active all along the session.

Like in PHP or every single language

Upvotes: 0

user2107733
user2107733

Reputation:

How session works?

HTTP is a stateless protocol.It means that it treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of requests and responses.

A stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests.

The protocol provides no means of storing a user's data between requests.

Therefore, we use Sessions, which allows us to chain multiple requests together into a conversation between client and server, so temporaly keep data.

Session is a hash, so you can add a data into session like to regular hash:

For example, to add a new order into the session can look like this:

e.g. OrdersController

def new
@order = current_user.orders.create   # creates a new order for current_user
session[:order] = @order.to_params    # adds order information to the session.
end

Sessions can store any kind of string data, but best served by keeping it as small as possible for both speed and security,as third party users can easily decode what information is stored in sessions.

UPDATE

by default session data are stored as cookies but Rails allows to configure session storage in database using ActiveRecordStore or inmemory storage with Redis and Redis store. Each approach has its advantages and disadvantages.

Upvotes: 2

jurglic
jurglic

Reputation: 3737

Try printing the session value instead of whole session object:

puts session[@request['user_id']]

Do this before and after setting a session. And make sure you cleanup the session before testing this in browser (clear cookies or start incognito session).

And last but not least, it a bad idea to store whole objects in session. This way you are storing way more data in the session than needed. Try storing just the object id (in your case @admin.id) and then load it whenever needed.

Upvotes: 1

Related Questions