Обычно я бы не хранил объекты в сеансе Rails, но я использую библиотеку, которая требует этого. Я столкнулся с очень странной проблемой, когда сохраненный объект отображается как строка после перенаправления.
Чтобы воспроизвести, я создал образец приложения Rails 4.1.
$ rails new session-test
Добавлен тестовый контроллер:
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
настроить маршруты:
Rails.application.routes.draw do
get 'home/index'
get 'home/from'
root 'home#index'
end
Затем я запускаю Rails
$ bundle exec rails server
и нажмите localhost:3000/home/from в браузере:
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'
Я понятия не имею, почему этот объект переводится как строка...
Похоже, это связано с типом хранилища сеансов cookie_store, потому что, если я изменю
session_store.rb из
Rails.application.config.session_store :cookie_store, key: '_session-test_session'
to
Rails.application.config.session_store :cache_store
оно работает!
Любые идеи?