簡體   English   中英

未定義的局部變量或方法“ current_user”可以

[英]undefined local variable or method `current_user' cancancan

我正在使用登錄/注銷系統。 我沒有使用devise,而是創建了一個活動記錄用戶模型,並使用會話來記住用戶是否登錄。一切正常,直到我在application_controller.rb添加這些行以在登錄前和登錄后進行布局。

layout :set_layout
  def set_layout
    if session[:current_user_id]
      'afterlogin'
    else
      'application'
    end
  end 

現在,在登錄並在html頁面的某處使用cancancan之后,我得到了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

添加該方法后是否應該對此進行修改?

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.

我建議您安裝Devise,以便它帶有一個免費的current_user方法。

僅供參考: https : //github.com/plataformatec/devise


UPDATE

用戶成功登錄后,可以在會話中存儲該用戶的ID。

session[:current_user_id]=user.id

這樣,在您的applicationcontroller中,您可以

 def current_user
    @current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) 
 end
 helper_method :current_user

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM