如何跨控制器中的多个操作存储实例变量? [英] How do I store an instance variable across multiple actions in a controller?

查看:32
本文介绍了如何跨控制器中的多个操作存储实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想在我的控制器中存储一些变量.我想在一个动作中初始化它,在另一个动作中增加它,然后在另一个动作中读取它.仅使用 @foo 声明此变量是行不通的,因为 @foo 在创建它的操作被呈现后死亡.
我不希望将此变量存储在模型中.

Say I want to store some variable in my controller. I want to initialize it in one action, increment it in another, and read it in yet another. Just declaring this variable with @foo doesn't work because @foo dies after the action that created it is rendered.
I do not want this variable to be stored in a model.

除了将其存储在会话中之外,还有其他方法可以保留此变量吗?
这个简单的问题我好像遇到过几次,我想知道解决它的最佳方法.

Is there a way to preserve this variable besides storing it in a session?
It seems like I've run into this simple problem a few times, and I want to know the best way to go about solving it.

推荐答案

并非如此.对控制器操作的每次调用都是无状态的.控制器操作完成后没有任何可用的内容.为每个请求创建一个新的控制器实例,然后在请求结束时丢弃.

Not really. Each call to a controller action is stateless. Nothing is available after the controller action finishes. A new controller instance is created for each request, and then discarded at the end of the request.

如果您不想将其存储在会话或数据库模型中,并且您希望该变量特定于特定会话,则您没有太多选择.

If you don't want to store it in the session, or database model, you don't have many options if you're wanting that variable to be specific to a particular session.

如果它在所有会话中都是全局的,你可以把它放在 @@class_variable 而不是 @instance_variable 中,但是一旦你开始有多个Rails 进程(每个进程都有自己的副本),或者如果您在线程安全模式下运行,最终可能会遇到严重的并发错误.

If it is global across all sessions, you could put it in a @@class_variable rather than an @instance_variable, but that can get messy once you start having multiple Rails processes (each which will have their own copy of it), or if you're running in threadsafe mode, you can end up with nasty concurrency bugs.

我想你可以看看 memcached 之类的东西,但你仍然需要把它输入到某个 user_id 或其他会话标记(除非它是全局的)

I guess you could look at something like memcached, but you'd still need to key that to some user_id or other session marker (unless it's global)

这篇关于如何跨控制器中的多个操作存储实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆