Kushal
Kushal

Reputation: 218

ruby on rails session data returns false even when data exists

I have a code like,

session[:my_data] = 'abcd'

and when i try to get,

puts session.has_key?("my_data") then it returns false always.

Upvotes: 1

Views: 323

Answers (1)

mihai
mihai

Reputation: 38543

Ruby allows any object to be a hash key. If the hash key is a symbol, you will not be able to access it using a string.

In this case, you have various options:

  • convert the string to a symbol

    session.has_key?("my_data".to_sym)

  • use Rails' with_indifferent_access method to allow both symbol and string queries on the hash

    s = session.with_indifferent_access puts s.has_key?("my_data")

Upvotes: 1

Related Questions