Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How does controller instance variables work

Good Morning, As a beginner to both Rails and web development, I don't know how to articulate my question so please feel free to rephrase.

I read that that a view in Rails gets the data to display via instance variables from the controller. I also read that an instance of the controller is created for each request. So my question is how does rails know which view gets which values assuming multiple simultaneuos requests? Since each controller instance is shared, is it wise to put values in the instance variables?

like image 384
rob Avatar asked Apr 08 '11 16:04

rob


People also ask

How do instance variables work?

Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables.

What is instance variable and how do you use it?

An instance variable is a variable that is specific to a certain object. It is declared within the curly braces of the class but outside of any method. The value of an instance variable can be changed by any method in the class, but it is not accessible from outside the class.

Can a Ruby module have instance variables?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.

What is difference between instance and variable?

They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to others. Class Variable: It is basically a static variable that can be declared anywhere at class level with static.


1 Answers

The answer is in your question my friend :

An intance of the controller is created on every request. Therefore, each request - IE each user browsing in firefox, each ajax request etc... - will instanciate a new controller. It's the rule in MVC that says a controller should be stateless for each request. That's your answer.

like image 78
Marcel Falliere Avatar answered Sep 19 '22 23:09

Marcel Falliere