How to specify a custom exception message from my .rb ability?

In my ability.rb , I have the following rule:

 elsif user.has_role? :demo can :read, Profile, demo_featured: true, demo_linked: true, message: "To access this profile, please subscribe here." 

But this does not create the message I want.

How do I get this particular rule to create the message I want?

Change 1

Here is the complete ability.rb if condition:

  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 

These are some bits from my 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 
+6
source share
3 answers

cancan docs give message customization examples when you authorize! in the controller, and when you manually raise an error, but there is no mechanism for specifying messages in ability.rb .

Instead, you can catch and modify it in your 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 
+2
source

Look for rescue_from CanCan::AccessDenied in your main application controller or in your specific controller. It should do something like redirecting to the login page. In my case, it is something like this:

 rescue_from CanCan::AccessDenied do || redirect_to new_user_session_path end 

Since you are creating another exception message and then displaying it, this will probably happen using flash:

 rescue_from CanCan::AccessDenied do |exception| flash[:notice] = exception.message redirect_to new_user_session_path end 

Your own logic may vary depending on how you want to handle when the user does not have access. Perhaps you can even configure it for each controller, but that should be its essence.

+1
source

Source: https://habr.com/ru/post/1013081/


All Articles