Helper methods allow controller methods to be called in the associated layout code.
# UserController helper_method def current_user @current_user ||= User.find(params[:id]) end
# User Show Page <h1>Hello, <%= current_user %></h1>
Why use a
A helper method is advantageous to use over an instance variable in a variety of ways.
- Instance variable value is set to
nilwhich can lead to unexpected results
def test @test end # test == nil
Instance variables are more difficult to maintain due to tracking of read and write, especially when
@objectis used in many places
Helper methods can return a more useful stack trace
Helper methods keep controller actions DRY
def edit end def update end def show end helper_method def active_record_object @object ||= ActiveRecordObject.find(params[:id]) end
I recommend replacing instance method calls with
helper_method’s in your Rails code!