Saturday, January 10, 2009

Access a method from both view and controller

If you need a method that will be accessed from both view and controller write the method in controller and pass the name of the function as an argument of helper_method.

class ApplicationController < ActionController::Base

..

..

def logged_in_user()
    user_id = session[:user_id]
    user = User.find_by_id(user_id)
    return user
  end

helper_method :logged_in_user

end

Here, logged_in_user method is accessible from all of the controllers those extend ApplicationController and helper_method :logged_in_user will expose this method to views. Your common accessible method signature may have arguments. But, only helper_method :logged_in_user is enough to make it accessible from view with the same signature defined.

2 comments:

Sohan said...

Learned a new trick in Rails. Thanks for putting this effort.

Ashrafuzzaman said...

Very useful for trick