Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails controllers and instance variables

A typical rails controller might do something like this:

class FoosController < ApplicationController
  def index
    @foos = Foo.all
  end
end

I understand rails well enough to know that @foos will return an array of Foo objects, but that @foos itself is an instance variable.

So which object does the instance variable belong to? Would it be an instance of the FoosController class? Is a different instance of this object created every time I access the index page? What about if I access the show page, where a new variable @foo is introduced:

def show
  @foo = Foo.find(params[:id])
end

Does this variable belong to the same object that @foos belongs to?

like image 399
stephenmurdoch Avatar asked Jun 07 '12 00:06

stephenmurdoch


1 Answers

  1. Correct; it belongs to the instance of FoosController that's processing the current request.
  2. Yes, each request creates a new instance of the controller–that's why instance variables can be used to hold state for a single request.
  3. Yes, but: if index isn't called, @foos won't be initialized, There is no @foos instance variable when the show action is hit in the code you show1.

1If you called index from show, then @foos would be initialized and available on the page. Not that you should do this, because that's confusing concerns.

like image 195
Dave Newton Avatar answered Nov 15 '22 08:11

Dave Newton