Rails 3.2.6. I have a following controller-view combination (simplified, in reality assignments are to results of some model calls):
def set_menu_vars @var1 = 1 @var2 = 2 end
SomeController < ApplicationController:
def some_action set_menu_vars end
corresponding (partial, shared) view (haml):
- if @var1 > 0 %p= @var1
So far so good, until I forget in some action to call
set_menu_vars - now I get an exception
undefined method '>' for nil:NilClass. This is quite understandable, and I want to ensure that if that partial view is used,
set_menu_vars is called automagically.
So I try to modify view as
- @controller.set_menu_vars ...
(googled) but get analogous exception saying that
nil. Well, these answers seem to be for Rails 2, seeing . I tried to change to
- controller.set_menu_vars ...
set_menu_vars is called successfully, but
@var1 is still
nil in the view.
So the question is: what is the right way to accomplish the task? Have a method in the controller for each of these variables (looking for instance variable to make the call to model at most once)? Or some other way?
UPD: the partial view in question is not directly relevant to the controller and its action. This is logically part of layout (dashboard showing links to groups of tasks that may require attention). So this is very natural for forget to call
set_menu_vars in several
if branches among about half of controller actions. On the other side,
set_menu_vars does some not so short queries to database, so I want it to be called if and only if it is needed (that is, if the view in question is really rendered).