通常我不会在 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
有用!
有任何想法吗?