Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Update: Original accepted answer was wrong</h2> <p>I'm leaving it below for now to demonstrate how wrong I was. After enough downvotes I have decided to look into how this actually works. My original answer was written after I was very new to rails and was an assumption based on how other MVC libraries I had used worked (specifically: CodeIgniter).</p> <h3>How it actually works (as of Rails 4)</h3> <p><code>AbstractController</code> (which <code>ActionController::Base</code> includes and your <code>ApplicationController</code> inherits from) includes a method called <a href="https://github.com/rails/rails/blob/618d5317d3ce3d40a22293149f79ff9843bbdb35/actionpack/lib/abstract_controller/rendering.rb#L65" rel="noreferrer">view_assigns</a>. This method grabs all the (non-protected) instance variables from the context of your controller and returns them in a hash. This method is consumed by instances of <code>ActionView::Base</code> (<a href="https://github.com/rails/rails/blob/618d5317d3ce3d40a22293149f79ff9843bbdb35/actionview/lib/action_view/rendering.rb#L70" rel="noreferrer">here</a>).</p> <p>So, basically, instance variables are provided to your view by a hash through a bit of meta-programming magic. Your view is definitely not executed in the context or scope of your controller. This is why you must explicitly declare controller methods as helper methods to make them visible to your views. That feature is enabled by separate layer of meta programming.</p> <h3>Original (wrong) answer:</h3> <p>It's not really that complicated or "meta". The <code>ActionController#render</code> method executes the template code (erb, haml, whatever) within the scope of the current <code>ApplicationController</code> instance. That means that all of the code within your template is executed inside of a method within your <code>ApplicationController</code>, and as such has access to the instances variables of the object it was executed inside of.</p> <p>If you don't call <code>render</code> then ApplicationController will try to figure out which template to call <code>render</code> with based on the action name.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload