how access to helper "current_user" in model rails?

Matrix picture Matrix · Dec 28, 2014 · Viewed 14k times · Source

I need to call current_user (define in ApplicationControler like an helper), in my User model.

I test ApplicationController.helpers.curret_user but not works:

irb(main):217:0> ApplicationController.helpers.current_user
NoMethodError: undefined method `current_user' for nil:NilClass

but this method works fine in controllers and views...

So how can I get my current user in model?

Answer

Simon1901 picture Simon1901 · May 20, 2015

if you in your ApplicationController call helper_method :current_user

class ApplicationController < ActionController::Base
  helper_method :current_user

  def current_user
    @current_user ||= User.find_by(id: session[:user])
  end
end

Than you can call it in your helpers

more docs on