Alex Kovshovik
Alex Kovshovik

Reputation: 4215

Why Rails 4.1 cookie session serializer converts nested session keys from symbols to strings?

My old application happens to use nested session keys like this:

session[:nested] = {some_id: 123}

This worked nicely in Rails version 4.0 and older, but with Rails 4.1 it is broken: nested session keys are de-serialized as strings, so I no longer can reference those nested values by a symbol as follows:

session[:nested][:some_id]

However, top-level session keys still work fine:

# First action that puts values into session.
def set_session_vars
  session[:some_id] = 321
  session[:nested] = {some_id: 123}
end

# Second action that loads values from session.
def set_session_vars
  root_id = session[:some_id] # => 321, works as expected.
  nested_id = session[:nested][:some_id] # => nil, THIS DOES NOT!
end

I understand that Rails 4.1 brings a rather significant change to the way session is serialized - it no longer uses Marshal.dump, instead it uses basic JSON serializer which doesn't serialize objects as is. It should however work fine for basic types like integers and strings which I use.

I tried using a "hybrid" session serializer, but that doesn't work either:

Rails.application.config.action_dispatch.cookies_serializer = :hybrid

Question: what can you recommend besides "don't use nested session keys"?

Thank you, Alex.

Upvotes: 1

Views: 1028

Answers (1)

mitsu
mitsu

Reputation: 473

I was faced with same problem. I know this isn't the answer which you want, but it works.

nested_id = session[:nested]['some_id'] # => 321

EDIT

After all, I changed :cookie_store to :active_record_store at config\initializers\session_store.rb

You don't need to change other code.

nested_id = session[:nested][:some_id] # => 321

Upvotes: 1

Related Questions