简体   繁体   English

Ruby On Rails控制器中的实例变量

[英]Instance variable in controller with Ruby On Rails

When someone is logging into my application, I use: 当有人登录我的应用程序时,我使用:

def create
    @user = User.authenticate(params[:email], params[:password])

    [...]
end

Ok, then, when someone is logging out: 那么,当有人注销时:

def destroy
    user = User.find_by_id(session[:user_id])

    [...]
end

Knowledge 知识

As far as I know, variable scopes work based on a scope , at least on Ruby (on Rails). 据我所知, variable scopes 基于作用域 ,至少在Ruby(on Rails)上。

Our friend said: 我们的朋友说:

In case of controllers, it present for that HTTP request alone, the object and the instance variables. 在控制器的情况下,它仅针对该HTTP请求,对象和实例变量。

Ok. 好。 My variable scope created on create method is useless for destroy method, but I was thinking about the subject and the following question appears: There's a way to preserve @user for that controller at all, regardless of the HTTP request? 我在create方法上create变量范围对于destroy方法没用,但是我正在考虑这个主题并出现以下问题: 无论HTTP请求如何,都有一种方法可以保留@user用于该控制器?

I mean, @ in this case seems useless to me because its not flexible. 我的意思是, @在这种情况下对我来说似乎没用,因为它不灵活。 I don't know, just sounds strange for me I can't reuse it when I want to. 我不知道,对我来说听起来很奇怪,我想不能重复使用它。

That's how the web works and why http is a 'stateless protocol'. 这就是网络的运作方式以及http为什么是“无状态协议”。 You must understand that you are not starting to run a program and stop it when your user logs out. 您必须了解您没有开始运行程序并在用户注销时将其停止。 But you 'restart' the program for every single request. 但是你为每一个请求“重新启动”程序。 It's a new instance, a new process that knows nothing of the last one and for sure shares no memory with it. 这是一个新的实例,一个对最后一个一无所知的新进程,并确保与它共享无记忆。 Actually the Rails instance that handles the create and the one that handles the destroy could easily run on two physically different servers! 实际上,处理创建的Rails实例和处理destroy的Rails实例可以轻松地在两个物理上不同的服务器上运行!

There is no state (but what you put in the session storage or the URL params). 没有状态(但是您在会话存储或URL参数中放置了什么)。 @ in this case means that your view can use this data (which in the Ruby context means that Rails already is doing some tricks to get it handed over there, since these are two different classes and the view would otherwise not know anything about the controllers instance variables). @在这种情况下意味着你​​的视图可以使用这个数据(在Ruby上下文中意味着Rails已经做了一些技巧来将它移交给那里,因为这些是两个不同的类,视图对控制器一无所知实例变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM