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


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’



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

def first
render plain: “.”

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


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


If I make a plain ruby program without rails

def aaa

def bbb
puts @z


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?


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.


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)