In rails, why can't one method see an instance variable created in another?


#1

In rails, why can’t one method see an instance variable created in another?

I have this code

Rails.application.routes.draw do

get ‘/qqq’, to: ‘application#first’
get ‘/rrr’, to: ‘application#second’

end

and

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception

def first
@v=“aaa”
render plain: “.”
end

def second
render plain: “X”+@v.to_s+“X”
end

end

I go to /qqq

then I go to /rrr

I expect XaaaX

But I get XX

For some reason, def second, cannot see the instance variable created in def first

However.

If I make a plain ruby program without rails

def aaa
@z=“fff”
end

def bbb
puts @z
end

aaa
bbb

then in that program, it works as expected, the bbb method sees the instance variable created in the aaa method.

Why though in rails, can one method not see the instance variable created in another method?


#2

Hi @barilo,

Visiting a page in Rails is a new HTTP request each time, and separate from previous requests. If you have a foo function that sets a variable, and you call that function in your code when visiting /rrr and try to print the variable, it’ll work then. As far as Rails is concerned, you sent two unrelated requests for two different pages, with two separate actions in the controller.


#3

Thanks, I see now from doing puts self, that each time a request is made leading an action to be called, it runs in a new class object / class instance. Whereas (a class variable like) @@v or (a global like) $v would work/cause XaaaX to be shown. (I know, one isn’t meant to use global/$)

(this would be true regardless of whether or not the actions show the same page or different pages, and even if there were just one action)


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.