Normally, I will not store objects in a Rails session, but I use a library that requires this. I ran into a very strange problem when a stored object appears as a string after a redirect.
To reproduce, I created a sample Rails 4.1 application
$ rails new session-test
Added test controller:
class HomeController < ApplicationController def index logger.debug "session[:customer]: #{session[:customer]}" logger.debug "session[:customer].name: #{session[:customer].name}" end def from Struct.new 'Customer', :name, :address session[:customer] = Struct::Customer.new 'Dave', '123 Main' redirect_to :action => :index end end
configuration routes:
Rails.application.routes.draw do get 'home/index' get 'home/from' root 'home#index' end
Then I run Rails
$ bundle exec rails server
and click localhost: 3000 / home / from in the browser:
Started GET "/home/from" for 127.0.0.1 at 2014-04-09 21:20:25 -0700 Processing by HomeController#from as HTML Redirected to http://localhost:3000/home/index Completed 302 Found in 18ms (ActiveRecord: 0.0ms) Started GET "/home/index" for 127.0.0.1 at 2014-04-09 21:20:25 -0700 Processing by HomeController#index as HTML session[:customer]: #<struct Struct::Customer name="Dave", address="123 Main"> Completed 500 Internal Server Error in 2ms NoMethodError (undefined method `name' for "#<struct Struct::Customer name=\"Dave\", address=\"123 Main\">":String): app/controllers/home_controller.rb:4:in `index'
I do not know why this object translates as String ...
This seems to be related to the cookie_store cookie storage type, because if I change
session_store.rb of
Rails.application.config.session_store :cookie_store, key: '_session-test_session'
to
Rails.application.config.session_store :cache_store
it works!
Any ideas?
Zack chandler
source share