[英]Rails Undefined Method Error for nil:NilClass
因此,在我的Rails應用程序中,我的用戶具有不同的權限。 有人登錄后,一切正常。 但是,當沒有人登錄時,出現以下錯誤:
Undefined method 'editor?' for nil:NilClass
def require_editor
redirect_to '/error' unless current_user.editor? || current_user.admin?
end
我想我完全理解發生這種情況的原因:因為沒有人登錄,Rails試圖弄清楚他們扮演的角色,並且因為沒有人登錄而沒有角色,所以Rails不知道它是否應該顯示頁面與否。
我的問題是:如何為未登錄的用戶設置默認角色,然后將其發送到錯誤頁面,提示他們沒有權限?
我通常會這樣:
class ApplicationController
def current_user_or_guest
current_user || Guest.new
end
class Guest
def editor?
false
end
def admin?
false
end
end
end
然后簡單地
def require_editor
redirect_to '/error' unless current_user_or_guest.editor? || current_user_or_guest.admin?
end
這可以通過使用CanCanCan並從控制器提取授權邏輯來簡化。 設置cancan功能后,控制器代碼通常如下所示:
def require_editor
redirect_to '/error' unless can?(:edit, MyThing)
end
def require_editor
redirect_to '/error' unless current_user && (current_user.editor? || current_user.admin?)
end
您當前正在呼叫editor?
在nil
對象上,這將引發錯誤。 通過使用上述技術,您首先要檢查以確保current_user
不為nil
,然后對current_user
是否存在進行檢查,如果不存在,則僅返回false並重定向到/error
URL。
在ApplicationController
創建一個重定向到錯誤頁面的方法,然后僅在您要確保用戶已登錄的操作上添加一個before_action
。
def require_editor
unless current_user && (current_user.editor? || current_user.admin?)
redirect_to '/error'
end
end
class Controller < ApplicationController
before_action :require_editor
def new
end
end
如果您使用的是devise
gem,則有一個用於要求身份驗證的回調/過濾器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.