Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you're looking for a way to associate complex logic with a particular view so that the logic is executed every time that view is created, even if it's generated with methods that don't exist yet, you can use Rails helpers. Every controller has a helper associated with it. For example, if you have a file <code>app/controllers/my_controller.rb</code>, Rails will automatically look for a file called <code>app/helpers/my_helper.rb</code>.</p> <p>Any methods defined in a helper are available to views that are created by the associated controller. So, for example, let's say you have this controller:</p> <pre><code>def MyController &lt; ApplicationController # snip ... def my_action @var = "some value" end end </code></pre> <p>and a view <code>app/views/my/my_action.html.erb</code>:</p> <pre><code>&lt;% variable1 = Model1.where(some conditions) %&gt; &lt;% variable2 = Model2.where(some other conditions) %&gt; &lt;% variable3 = Model3.where(some third conditions) %&gt; &lt;%= "#{variable1} #{variable2} #{variable3} #{@var} %&gt; </code></pre> <p>You can refactor the code that accesses the models into <code>app/helpers/my_helper.rb</code>:</p> <pre><code>module MyHelper def get_variable1() return Model1.where(some conditions) end def get_variable2() return Model2.where(some other conditions) end def get_variable3() return Model3.where(some third conditions) end end </code></pre> <p>And refactor your view like this:</p> <pre><code>&lt;% variable1 = get_variable1() %&gt; &lt;% variable2 = get_variable2() %&gt; &lt;% variable3 = get_variable3() %&gt; &lt;%= "#{variable1} #{variable2} #{variable3} #{@var} %&gt; </code></pre> <p>Without having to modify your controller.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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