【发布时间】:2014-05-23 14:36:38
【问题描述】:
通常我不会在 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'
到
Rails.application.config.session_store :cache_store
有效!
有什么想法吗?
【问题讨论】:
-
有问题的库是许多开发人员使用的 shopify_app gem。我同意在 Rails 会话中存储对象是一个坏主意,原因有很多,但这就是这个 gem 的作用:github.com/Shopify/shopify_app/blob/master/lib/generators/… 我想知道为什么这在 Rails 4.1 中很无聊?我在他们的示例应用程序 3.2 中没有看到它发生:github.com/Shopify/embedded-app-example
标签: ruby-on-rails session ruby-on-rails-4 shopify ruby-on-rails-4.1