[英]How do I specify a custom exception message from my ability.rb?
在我的ability.rb
,我有以下規則:
elsif user.has_role? :demo
can :read, Profile, demo_featured: true, demo_linked: true, message: "To access this profile, please subscribe here."
但那不會產生我想要的信息。
如何獲得此特定規則以生成我想要的消息?
編輯1
這是完整的ability.rb
if
條件:
def initialize(user)
user ||= User.new # guest user (not logged in)
alias_action :create, :show, :new, :destroy, to: :csnd
if user.has_role? :admin
can :manage, :all
elsif user.has_role? :coach
# do some stuff
elsif user.has_role? :demo
can :read, Profile, demo_featured: true, demo_linked: true
elsif user.has_role? :player
# can do some stuff
else
can :read, Profile
end
end
這些是我的ProfilesController
中的一些內容:
before_action :set_profile, only: [:show, :edit, :update, :destroy, :invite_user, :profiles]
def set_profile
@profile = Profile.published.includes(:grades, :positions, :achievements, :videos, :transcripts).friendly.find(params[:id])
end
cancan文檔提供了在您authorize!
時自定義消息的示例authorize!
在控制器中,當您手動引發錯誤時,似乎沒有任何機制可以在ability.rb
指定消息。
相反,您可以在ApplicationController
捕獲並修改它:
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied do |exception|
if current_user.has_role? :demo
redirect_to :back, :alert => "To access this profile, please subscribe here."
end
# render 403, etc.
end
end
在主應用程序控制器或特定控制器中查找rescue_from CanCan::AccessDenied
。 它應該像重定向到登錄頁面。 就我而言,它是這樣的:
rescue_from CanCan::AccessDenied do ||
redirect_to new_user_session_path
end
既然你正在生成一個不同的異常消息然后顯示它,它可能是這樣的,使用flash:
rescue_from CanCan::AccessDenied do |exception|
flash[:notice] = exception.message
redirect_to new_user_session_path
end
您自己的邏輯可能會有所不同,具體取決於您在用戶無權訪問時的處理方式。 您可能甚至可以在每個控制器的基礎上進行設置,但這應該是它的要點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.