Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Common method available for controllers and views?

I have been working with Ruby on Rails for a short time. Recently I implemented an authentication system for my application. I made a method available on 'application_helper.rb' to retrieve the current logged user (method called current_user).

The method just retrieves my User object if the session[:user_id] variable is present.

However I face the following problem.

  1. If I place the current_user method in 'application_helper.rb', my controllers can't make use of it
  2. If I place the current_user method in 'application_controller.rb', my views can't make use of it

What's the best approach to solve this problem? The easy way would be duplicate my code in both controller and helper, but I know there is a better and more correct way.

Thanks in advance

like image 247
lupidan Avatar asked Jun 06 '14 18:06

lupidan


1 Answers

This is a common and well-solved problem.

Rails doesn't allow controllers to access helper methods. If you want to share a method between your views and controllers, you need to define the method in your controller, and then make it available to your views with helper_method:

class ApplicationController < ActionController::Bbase

  # Let views access current_user
  helper_method :current_user

  def current_user
    # ...
  end

end

You can pass more than one method name to helper_method to make additional methods in your controller available to your views:

  helper_method :current_user, :logged_in?

  def current_user
    # ...
  end

  def logged_in?
    !current_user.nil?
  end
like image 157
meagar Avatar answered Oct 12 '22 22:10

meagar