Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of an instance variable in a Rails controller?

If I create an instance variable in a Rails controller, what is the scope of that instance variable? Is it available to all of the Rails application, or just to the views and models associated with that particular controller? Since I am new to Rails, I am a bit confused.

like image 617
chandradot99 Avatar asked Feb 08 '23 13:02

chandradot99


1 Answers

An instance variable in a Rails controller is used in two ways:

  • It is available within instance methods of that controller (including superclass instance methods), just like any other Ruby instance variable.
  • When a Rails controller action renders a view, the controller's instance variables are copied (shallowly) to the view instance. (The view instance is the value of self within a template.) Controller instance variables defined at the time an action renders are therefore effectively available within that action's view. View helpers are just modules which are extended by the view instance, so controller instance variables are effectively available within view helper methods too.

    Note that although controller instance variables are copied to the view, instance variables defined in the view are not copied back to the controller. That's not something you'd normally need to have happen because rendering the view is normally the last thing done in a controller action. And local variables defined in a view are available throughout the view, so there's no reason at all to define an instance variable in a view.

An instance variable in a given controller is not available within other controllers, within other controllers' views, or within any models at all.

like image 188
Dave Schweisguth Avatar answered Apr 12 '23 23:04

Dave Schweisguth