5

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?

1 Answer 1

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

1 If 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Good explanation. To add, @foos is an array containing instances of the Foo objects.
@Anil Thanks. I think the OP mentioned what @foos contains, so I didn't add it :)
I know you don't miss anything. But I like it when I can get all my knowledge in one spot. This is the type of question which helps the OP a little now, but has a long term value to the communtiy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.