未定义的局部变量或方法 `current_user' cancancan

Bog*_*iel 1 ruby-on-rails

我正在开发登录/注销系统。我没有使用设计,而是创建了一个活动记录用户模型并使用会话来记住用户是否登录。一切正常,直到我application_controller.rb在登录前和登录后添加这些行以具有布局。

layout :set_layout
  def set_layout
    if session[:current_user_id]
      'afterlogin'
    else
      'application'
    end
  end 
Run Code Online (Sandbox Code Playgroud)

现在,在我登录并cancancan在 html 页面的某处使用后,我得到undefined local variable or method 'current_user'. 我认为我必须添加一个current_user方法,但我不知道在哪里以及如何定义它。

编辑:我在登录使用的另一个类中已经有了类似的东西:

class Admin::ApplicationController < ApplicationController
    before_action :authorize

  def authorize
  begin
    @current_user ||= User.find(session[:current_user_id]) if session[:current_user_id]
  rescue ActiveRecord::RecordNotFound
    session.destroy
    redirect_to '/login',alert: 'Please login'
  end
end

end
Run Code Online (Sandbox Code Playgroud)

添加该方法后,我应该修改它吗?

Jef*_*son 5

CanCanCan expects a current_user method to exist in the controller. 
First, set up some authentication (such as Authlogic or Devise). 
See Changing Defaults if you need different behavior.
Run Code Online (Sandbox Code Playgroud)

我建议您安装 Devise,以便它带有一个免费的 current_user 方法。

仅供参考:https : //github.com/plataformatec/devise


更新

当用户登录成功时,您可以将用户的 id 存储在 session 中。

session[:current_user_id]=user.id
Run Code Online (Sandbox Code Playgroud)

这样,在您的应用程序控制器中,您就可以执行

 def current_user
    @current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) 
 end
 helper_method :current_user
Run Code Online (Sandbox Code Playgroud)