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
但这种方法在控制器和视图中工作正常......
那么如何让我当前的用户进入模型?
你不能(或者,至少,你真的不应该).
您的模型根本无法访问当前实例化的控制器.你的模型应该以这样的方式,有可能甚至没有被设计成为一个请求或实际上与系统(认为交互交互用户ActiveJob).
您需要传递current_user 到模型层.
你的具体问题是你发明了一种叫做的东西helpers.这不是一件事,它是nil,所以你得到你NoMethodError的nil:nilClass错误.current_user是一个实例方法,因此您需要直接在控制器的实例上调用它,而不是在类本身上调用它.
如果您在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
你可以在助手中调用它
我只是在这里回答: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
这将向后遍历堆栈以寻找响应 的帧current_user。如果没有找到,则返回 nil。通过确认预期的返回类型,并可能通过确认框架的所有者是一种控制器,它可以变得更加健壮,但通常只是花花公子。
| 归档时间: | 
 | 
| 查看次数: | 12841 次 | 
| 最近记录: |