我使用cancan管理用户和管理员角色。我希望用户能够访问某些视图(" Cursos"," Credenciales"),但cancan不允许。我怎样才能让他们访问?所以,正在发生的是它尝试访问路由但返回到根,因为我指定它在应用程序控制器中执行它。 (当然它应该通过那条路线访问控制器。)感谢您的帮助!!
<% if current_user %>
<% if can? :new, @user %>
<% if can? :new, @empleado %>
<li><%= link_to "Lista de Empleados", empleados_path %></li>
<li> <%= link_to "Agregar Empleado", new_empleado_path %></li>
<% end %>
<% end %>
<li><%= link_to "Cursos", cursovence_path %></li>
<li><%= link_to "Credenciales", credencialvence_path %></li>
<% end %>
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :all
else
can :read, :all
can :display, :all
end
end
devise_for :users
root 'empleados#index'
resources :empleados
resources :users
post '/empleados/:id' => 'empleados#display'
get '/cursovence' => 'empleados#indexCursoVence'
get '/credencialvence' => 'empleados#indexCredencialVence'
get '/proxvacas' => 'empleados#indexProxVacas'
class EmpleadosController < ApplicationController
before_action :authenticate_user!
# load_and_authorize_resource - It did not work with this validation
load_resource #So, I changed it for only this one
def index
....
end
def new
....
end
end
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = "Access denied."
redirect_to root_url
end
end
答案 0 :(得分:1)
在康康舞中,你可以根据符号而不是类别来分配能力(如果你没有基于你的能力的模型)https://github.com/ryanb/cancan/wiki/Non-RESTful-Controllers
因此,在您的视图中,检查can? :index, :cursos
和can? :index, :credenciales
,因为您已在您的能力中添加了can :read, :all
<% if can? :index, :cursos %>
<li><%= link_to "Cursos", cursovence_path %></li>
<% end %>
<% if can? :index, :credenciales %>
<li><%= link_to "Credenciales", credencialvence_path %></li>
<% end %>