Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how access to helper "current_user" in model rails? [duplicate]

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?

like image 241
Matrix Avatar asked Dec 28 '14 02:12

Matrix


3 Answers

I just answered this here: https://stackoverflow.com/a/1568469/2449774

Copied for convenience:

I'm always amazed at "just don't do that" responses by people who know nothing of the questioner's underlying business need. Yes, generally this should be avoided. But there are circumstances where it's both appropriate and highly useful. I just had one myself.

Here was my solution:

def find_current_user
  (1..Kernel.caller.length).each do |n|
    RubyVM::DebugInspector.open do |i|
      current_user = eval "current_user rescue nil", i.frame_binding(n)
      return current_user unless current_user.nil?
    end
  end
  return nil
end

This walks the stack backwards looking for a frame that responds to current_user. If none is found it returns nil. It could be made more robust by confirming the expected return type, and possibly by confirming owner of the frame is a type of controller, but generally works just dandy.

like image 51
keredson Avatar answered Nov 19 '22 15:11

keredson


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

like image 43
Simon1901 Avatar answered Nov 19 '22 14:11

Simon1901


You can't (or, at the very least, you really really shouldn't).

Your models have no access at all to your currently instantiated controller. Your models are supposed to be designed in such a way that there might not even be a request or a user actually interacting interactively with the system (think ActiveJob).

You need to pass current_user into your model layer.


Your specific problem is that you've invented something called helpers. That isn't a thing, it's nil, so you get your NoMethodError on nil:nilClass error. current_user is an instance method, so you would need to invoke it directly on an instance of your controller, not on the class itself.

like image 7
meagar Avatar answered Nov 19 '22 13:11

meagar