Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 that doesn't produce the message I want.

How do I get this specific rule to produce the message I want?

Edit 1

Here is the full 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
like image 521
marcamillion Avatar asked Dec 12 '16 07:12

marcamillion


2 Answers

This is what you are looking for:

https://github.com/CanCanCommunity/cancancan/wiki/Exception-Handling

like image 93
Astranormal Avatar answered Oct 18 '22 09:10

Astranormal


The cancan docs give examples of customizing the message when you authorize! in the controller, and when you manually raise an error, but there doesn't seem to be any mechanism for specifying messages in ability.rb.

Instead, you could 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
like image 32
anyarms Avatar answered Oct 18 '22 08:10

anyarms