ruby-on-rails – 存储在Rails会话中的对象变成了一个String?
通常我不会在Rails会话中存储对象,但我使用的是需要它的库.我遇到了一个非常奇怪的问题,即重定向后存储的对象显示为String.
为了重现我已经创建了一个示例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 /: 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' 我不知道为什么这个对象被翻译为String … 它似乎与cookie_store的会话存储类型有关,因为如果我改变了 session_store.rb来自 Rails.application.config.session_store:cookie_store,key:’_ session-test_session’ 至 Rails.application.config.session_store:cache_store 有用! 有任何想法吗? 解决方法
您无法在Rails会话中存储对象.它是一个只接受字符串的键值存储,因为它经常被打包并作为加密cookie发送给客户端.
对于您可能需要的东西,它不是倾倒场.注意你在那里塞满了多少垃圾,因为你越倾向于会话,cookie越大,客户端就必须为每个请求回到你的服务器. 值得观察浏览器网络检查工具中的标题,以了解您的请求占用的空间有多大. 如果你确实需要在那里保留一些内容,请使用像JSON这样的字符串友好的编码格式,以确保可以以可用的格式恢复数据. 我也非常犹豫使用cache_store,它不会在应用程序的不同实例之间共享. Ruby对象只存在于单个进程的上下文中,因此其他请求(通常不会触及某些随机进程)将无法轻松地使用它. 默认的cookie存储是最可靠的.在进程之间共享的其他服务依赖于正在运行的其他服务(Memcached,Redis等),但其中大多数也规定了仅字符串策略. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |