ruby-on-rails - 允许使用 cancancan 访问不同的 View 和路线?

标签 ruby-on-rails cancan

我正在使用 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/

相关文章:

SQL 其中连接集必须包含所有值但可能包含更多

ruby-on-rails - 将默认角色添加到 Devise 用户模型

ruby-on-rails - 向 Rails Composer、Devise、CanCan、Twitter Bootstrap 添加角色

ruby-on-rails - 您的包被锁定为 mimemagic (0.3.5),但在您的 Gemfile 中列出的任何来源中都找不到该版本

ruby-on-rails - will_paginate 呈现空白结果

ruby-on-rails - 使用 cancan 让用户只管理一些模型

ruby-on-rails - 了解康康舞能力

ruby-on-rails - devise/cancan模拟帐户

ruby-on-rails - centos上安装resque Brain时出错

ruby-on-rails - JSON 参数在请求哈希中不可用(Rails、omniauth-google-oauth2 gem)