I did code for dynamically permission from admin side using cancan gem.
when i give permission for all and read / create. it will work but when i give permission for modle_name and read/create. it will show me Access denied. when permission is exist for that.
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
logger.info("<.............#{exception.inspect}...........>")
flash[:alert] = "Access denied. You are not authorized to access the requested page."
redirect_to user_root_path
end
protected
#derive the model name from the controller. egs UsersController will return User
def self.permission
return name = self.name.gsub('Controller','').singularize.split('::').last.constantize.name rescue nil
end
def current_ability
@current_ability ||= Ability.new(current_user)
end
#load the permissions for the current user so that UI can be manipulated
def load_permissions
@current_permissions = current_user.roles.each do|role|
end
end
end
class Ability
include CanCan::Ability
def initialize(user)
user.roles.each do|role|
role.permissions.each do |permission|
if permission.subject_class == "all"
can permission.action.to_sym, permission.subject_class.to_sym
else
can permission.action.to_sym, permission.subject_class.constantize
end
end
end
end
end
when i give permission like this:
permission.subject_class = PublicDoc
permission.action = create
is will show me error in console form
<....CanCan......:public_doc...........>
<....CanCan......:new...........>
<....CanCan......#<CanCan::AccessDenied: You are not authorized to access this page.>...........>
I did some code like this.
please help me to solve this. Thank you.
I edited my Ability class to this:
class Ability
include CanCan::Ability
def initialize(user)
user.roles.each do|role|
role.permissions.each do |permission|
if permission.subject_class == "all"
can permission.action.to_sym, permission.subject_class.to_sym
else
can permission.action.to_sym, permission.subject_class.to_sym
end
end
end
end
end
and passed value in permission like below.
permission.subject_class = public_doc
permission.action = create
this is worked for me. :)