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
This is what you are looking for:
https://github.com/CanCanCommunity/cancancan/wiki/Exception-Handling
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With