允许使用 cancancan 访问不同的视图和路线?

Allow access to different views and routes with cancancan?

我正在使用 cancan 管理用户和管理员角色。我希望用户可以访问某些视图 ("Cursos", "Credenciales", ) 但 cancan 不允许这样做。我怎样才能给他们访问权限?所以,发生的事情是它尝试访问路由,但返回到根目录,正如我在应用程序控制器中指定的那样。 (当然应该是通过那个路由访问controller。)感谢您的帮助!!

index.html.erb

<% 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 %>

ability.rb

include CanCan::Ability
def initialize(user)
  user ||= User.new 
  if user.admin?
    can :manage, :all
  else
    can :read, :all
    can :display, :all
  end
end

routes.rb

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'

empleados_controller.rb

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                                                 

application_controller.rb

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

在康康中,您可以根据符号而不是 类 分配能力(以防您没有模型作为能力的基础)https://github.com/ryanb/cancan/wiki/Non-RESTful-Controllers

所以在你看来检查 can? :index, :cursoscan? :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 %>