higan96技術メモ

https://github.com/higan96

sessionに保存されたHashの挙動がストア前後で変わる。

sessionに保存されたHashの挙動がストア前後で変わる。

session[:test_data] = {hoge: ‘fizz’, fuga: ‘buzz’ }

としたとき、session[:test_data]の中身は

{:hoge =>’fizz’, :fuga => ‘buzz’}

となる。
しかしこれが別のアクションで使用するとき、つまり一度ストアされると、

{‘hoge’ =>’fizz’, ‘fuga’ => ‘buzz’}

このように、keyがシンボルから文字列に変わっている。

これ、stackoverflowにも質問がありました。
session - Ruby on Rails sneakily changing nested hash keys from symbols to strings - Stack Overflow
回答

Sessions, if you're using cookie ones, do not live in Ruby - they are transmitted back and forth across the network. The session object you stored your data in is not the same session object that you tried to read it from. And while in cookie form, there is no difference between strings and symbols. Use Hash#symbolize_keys! to be sure you have your keys as you wish, or just use the string keys consistently.

解決方法としては

  • シンボルではなく文字列を使う
  • symbolize_keys!を使用する

ということらしい。

cookieの仕様っぽいですね。