Question

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).

Our friend said:

In case of controllers, it present for that HTTP request alone, the object and the instance variables.

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?

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.

Was it helpful?

Solution

That's how the web works and why http is a 'stateless protocol'. 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!

There is no state (but what you put in the session storage or the URL params). @ 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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top