Search code examples
ruby-on-railsrubysessionopenstruct

How OpenStruct stored in session


I have some controller. In this controller I get OpenStruct object and want to save it to app session. Next code works fine:

session[:info] = OpenStruct.new(first_field: 1, second_field: 'two')

p session[:info] right after this line prints

#<OpenStruct first_field=1, second_field="two">

But after this I do redirect to another controller, and when I write p session[:info] in this controller I get

{"table"=>{"first_field"=>1, "second_field"=>"two"}}

So, why do I get this, and how can I load correct OpenStruct instance?


Solution

  • A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client.

    You should either serialize your objects before storing them in the session.

    session[:info] = OpenStruct.new(first_field: 1, second_field: 'two').to_yaml
    

    and retrieve it using

    YAML.load(session[:info])
    

    from the rails documentation

    Do not store large objects in a session. Instead you should store them in the database and save their id in the session. This will eliminate synchronization headaches and it won't fill up your session storage space (depending on what session storage you chose, see below). This will also be a good idea, if you modify the structure of an object and old versions of it are still in some user's cookies. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate.

    or change your session store from cookie_store to cache_store

    In your environment change

    config.session_store :cookie_store
    

    to

    config.session_store :cache_store