如何在模型轨道中访问辅助"current_user"?

Mat*_*rix 9 controller model helper ruby-on-rails-4

我需要在我的User模型中调用current_user(在ApplicationControler中定义,就像帮助器一样).

我测试ApplicationController.helpers.curret_user但不起作用:

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

但这种方法在控制器和视图中工作正常......

那么如何让我当前的用户进入模型?

mea*_*gar 7

你不能(或者,至少,你真的不应该).

您的模型根本无法访问当前实例化的控制器.你的模型应该以这样的方式,有可能甚至没有被设计成为一个请求或实际上与系统(认为交互交互用户ActiveJob).

您需要传递current_user 模型层.


你的具体问题是你发明了一种叫做的东西helpers.这不是一件事,它是nil,所以你得到你NoMethodErrornil:nilClass错误.current_user是一个实例方法,因此您需要直接在控制器的实例上调用它,而不是在类本身上调用它.

  • @Matrix你应该放弃自由选择.在Rails中有非常强烈定义的约定,你应该遵循它们,特别是在你不知道选择哪些约定可以安全地被忽视的开始时.Rails作为一个整体是非常强大的,但它为你做了很多*,但只有你真正正确地使用它. (3认同)

Sim*_*901 6

如果您在ApplicationController中调用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
Run Code Online (Sandbox Code Playgroud)

你可以在助手中调用它

更多文档


ker*_*son 6

我只是在这里回答:https : //stackoverflow.com/a/1568469/2449774

复制方便:

我总是对那些对提问者的潜在业务需求一无所知的人的“不要那样做”的回答感到惊讶。是的,通常应该避免这种情况。但在某些情况下,它既合适又非常有用。我自己只有一个。

这是我的解决方案:

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
Run Code Online (Sandbox Code Playgroud)

这将向后遍历堆栈以寻找响应 的帧current_user。如果没有找到,则返回 nil。通过确认预期的返回类型,并可能通过确认框架的所有者是一种控制器,它可以变得更加健壮,但通常只是花花公子。