Rails CANCAN - 第一次点击无访问权限

Rails CANCAN - No Access on first click

我在使用 Rails 4 和 CanCan 时遇到了一些问题。 我所做的一切都像这里描述的那样 https://github.com/ryanb/cancan 实际上它有效但我有以下问题:

有时当我点击导航中的 link 时,例如"Employee" 打开 Employee/Show 页面 CanCan 发出警报:

"...employee/?alert=You+are+not+authorized+to+access+this+page"

我将重定向到主页。

当我再次单击同一个 link 时,页面将打开。现在没有访问问题...

我不知道这个问题的原因是什么...:(

希望有人能帮忙。

一些代码:

ability.rb

def initialize(user)

    if user.admin?
      can :manage, :all

    elsif user.secretary?
      can :manage, :all       

      cannot [:destroy],[Employee, Setting, Section, Role, Position]

    elsif user.leader? 
      can :manage, :all

      cannot [:manage],[Setting, Section, Role, Position]
      cannot [:destroy],[Project, Customer, Distributor]
      cannot [:destroy, :edit],[Employee]


    elsif user.employee?
      can :manage, :all

      cannot [:manage],[Setting, Section, Role, Position, Employee, Customer, Distributor]
      cannot [:destroy, :edit],[Project]

    else
      #can :read, :all
    end
end

employees_controller.rb

class EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :edit, :update, :destroy]
#before_action :set_tmpPswVar, only: [:show]

#CanCan
load_and_authorize_resource

...

application_controller.rb

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
include SessionsHelper
before_action :require_login
protect_from_forgery with: :exception

#load_and_authorize_resource
#CanCan
skip_authorization_check

#for CanCan version necessary because is not optimized for rails 4
#without that eacht create method will generate an ForbiddenAttributeError!
 before_filter do
    resource = controller_name.singularize.to_sym
   method = "#{resource}_params"
   params[resource] &&= send(method) if respond_to?(method, true)
 end


 #CANCAN
 rescue_from CanCan::AccessDenied do |exception|
   redirect_to :controller=>"workdays", :action => "index", :alert =>    exception.message
 end

 ...

此致 库玛洛

遗憾的是 CanCan 不支持 Rails 4+。你应该改用 CanCanCan:

https://github.com/CanCanCommunity/cancancan