Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In my point of view, all your logic should be placed in your controller, models, helpers or libraries. In your case, setting variables should be done in your controller and not in your views.</p> <p>It's really interresting to place your logic at the good place, because it will be more easy to debug, maintain or refactore your application if your code is at the good place.</p> <p>So, here are some ideas to put your variables declarations in your controller without duplicate your code :)</p> <h2>before_action (in controller)</h2> <p>You can use <code>before_action</code> in your controller. It will reduce the duplicated code.</p> <p>For example, you can do:</p> <pre><code>before_action :set_variables def set_variables @var1 = some_code @var2 = other_code ... end </code></pre> <p>You can restrict the before_action to only specific actions by using <code>only</code> or <code>except</code></p> <pre><code>before_action :set_variables, only: [:index, :edit] </code></pre> <p>This will call set_variables only before index and edit</p> <h2>before_action (in application_controller.rb)</h2> <p>If you want to add a before_action for all index actions in every controllers for examples, you just have to do a before_action in your application_controller.rb</p> <p>And if you want to skip this type of before_action in a specific controller, you can use the skip_before_action method.</p> <pre><code># application_controller.rb before_action :set_variables, only: :index # specific_controller.rb skip_before_action :set_variables </code></pre> <h2>One more thing: model scopes</h2> <p>Then, a last thing before the end: <code>Model1.where(some conditions)</code>. What about model scopes?</p> <p>Your code will be more readable and less duplicated:</p> <pre><code>class MyModel &lt; ActiveRecord::Base scope :active, -&gt; { where(is_active: true) } end MyModel.active # equivalent to MyModel.where(is_active: true) </code></pre>
    singulars
    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.
    3. VO
      singulars
      1. This table or related slice is empty.
    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