【问题标题】:Rails CANCAN - No Access on first clickRails CANCAN - 第一次点击无访问权限
【发布时间】:2023-10-23 09:59:01
【问题描述】:

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

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

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

然后我将重定向到主页。

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

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

希望有人能帮忙。

一些代码:

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

 ...

最好的问候 熊吕

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 cancan


    【解决方案1】:

    很遗憾,CanCan 不支持 Rails 4+。您应该改用 CanCanCan:

    https://github.com/CanCanCommunity/cancancan

    【讨论】:

    • 嗯,好吧,我知道 CanCan 没有针对 Rails 4 进行优化,但我不知道有 CanCanCan 解决方案。我会试试!谢谢!
    • 我已经测试过了......现在我在登录警报后直接获得,但之后就没有问题了。还可以,比以前更好,但还是很奇怪……
    • 现在我还是有同样的问题:(...对不起