OpenStruct是如何存储在session中的
How OpenStruct stored in session
我有一些控制器。在这个控制器中,我得到了 OpenStruct 对象并想将它保存到应用程序会话中。下一个代码工作正常:
session[:info] = OpenStruct.new(first_field: 1, second_field: 'two')
p session[:info]
在这行打印
之后
#<OpenStruct first_field=1, second_field="two">
但在这之后我会重定向到另一个控制器,当我在这个控制器中写 p session[:info]
时,我得到
{"table"=>{"first_field"=>1, "second_field"=>"two"}}
那么,为什么我得到这个,我怎样才能加载正确的 OpenStruct 实例?
A session usually consists of a hash of values and a session id,
usually a 32-character string, to identify the hash. Every cookie sent
to the client's browser includes the session id. And the other way
round: the browser will send it to the server on every request from
the client.
您应该在将对象存储到会话之前序列化它们。
session[:info] = OpenStruct.new(first_field: 1, second_field: 'two').to_yaml
并使用
检索它
YAML.load(session[:info])
来自 rails 文档
Do not store large objects in a session. Instead you should store them
in the database and save their id in the session. This will eliminate
synchronization headaches and it won't fill up your session storage
space (depending on what session storage you chose, see below). This
will also be a good idea, if you modify the structure of an object and
old versions of it are still in some user's cookies. With server-side
session storages you can clear out the sessions, but with client-side
storages, this is hard to mitigate.
或将您的会话存储从 cookie_store
更改为 cache_store
在你的environment
改变
config.session_store :cookie_store
到
config.session_store :cache_store
我有一些控制器。在这个控制器中,我得到了 OpenStruct 对象并想将它保存到应用程序会话中。下一个代码工作正常:
session[:info] = OpenStruct.new(first_field: 1, second_field: 'two')
p session[:info]
在这行打印
#<OpenStruct first_field=1, second_field="two">
但在这之后我会重定向到另一个控制器,当我在这个控制器中写 p session[:info]
时,我得到
{"table"=>{"first_field"=>1, "second_field"=>"two"}}
那么,为什么我得到这个,我怎样才能加载正确的 OpenStruct 实例?
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client.
您应该在将对象存储到会话之前序列化它们。
session[:info] = OpenStruct.new(first_field: 1, second_field: 'two').to_yaml
并使用
检索它YAML.load(session[:info])
来自 rails 文档
Do not store large objects in a session. Instead you should store them in the database and save their id in the session. This will eliminate synchronization headaches and it won't fill up your session storage space (depending on what session storage you chose, see below). This will also be a good idea, if you modify the structure of an object and old versions of it are still in some user's cookies. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate.
或将您的会话存储从 cookie_store
更改为 cache_store
在你的environment
改变
config.session_store :cookie_store
到
config.session_store :cache_store