我正在使用 cancan 管理用户和管理员角色。我希望用户可以访问某些 View (“Cursos”、“Credenciales”、),但 cancan 不允许这样做。我怎样才能给他们访问权限?所以,发生的事情是它尝试访问路由,但返回到根目录,正如我在应用程序 Controller 中指定的那样。 (当然应该通过那个路由访问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 %>
能力.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
路线.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
应用程序 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
那么在你看来检查可以吗? :index, :cursos
和 可以吗? :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 %>
关于ruby-on-rails - 允许使用 cancancan 访问不同的 View 和路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662526/