Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 helper method available in model

I'm upgrading an app to Rails 3. We have an Application Controller like the following:

class ApplicationController < ActionController::Base
     helper_method :current_user

     def current_user
       @current_user ||= User.find(session[:user_id]) if session[:user_id]
     end

Because we define "helper_method", "current_user" is available to all the views. It's available to the controllers because they all inherit from class ApplicationController.

However, when we were on 2.3.8, access to "current_user" was available through a model, but now it's not. Is there a way to get this exposed to the models?

like image 441
user577808 Avatar asked Apr 02 '11 17:04

user577808


People also ask

What are helper methods in Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.


1 Answers

I could suggest moving current_user into a helper like UserHelper, then you can include it in your model with include UserHelper.

You'll also have to include UserHelper in your ApplicationController, but helper :user will include that like normal into your views too.

like image 137
Kelly Avatar answered Oct 30 '22 02:10

Kelly