Ruby on Rails: a generic method for controllers and views?

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

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

However, I am facing the following problem.

  • If I put the current_user method in 'application_helper.rb', my controllers will not be able to use it
  • If I put the current_user method in 'application_controller.rb', my views will not be able to use it

What is the best approach to solve this problem? A simple way would be to duplicate my code both in the controller and in the assistant, but I know that there is a better and correct way.

Thank you in advance

+6
source share
1 answer

This is a common and well-resolved issue.

Rails does not allow controllers to access helper methods. If you want to share a method between your views and controllers, you need to define a method in your controller and then make it available to your views using 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 add additional methods to your controller to your views:

  helper_method :current_user, :logged_in? def current_user # ... end def logged_in? !current_user.nil? end 
+6
source

Source: https://habr.com/ru/post/970480/


All Articles