【问题标题】:CanCan not fully supported in Rails 4 [closed]Rails 4 不完全支持 CanCan [关闭]
【发布时间】:2013-12-10 04:46:43
【问题描述】:

Ryan Bates 似乎停止开发 CanCan。没有完全支持 Rails 4。而且,ready4rails4 说它不起作用。

我应该将 CanCan 替换为另一个授权库吗?

问候

【问题讨论】:

  • 在 Rails 4 出来之前很久他就停止了开发。
  • 我知道,所以我需要知道另一个库
  • 始终检查 The Ruby Toolbox 以获取 gem 替代品。所以忽略cancan 这仍然是最常用的宝石,我们有 3 种选择。 declarative_authorization 似乎真的很复杂,rolify 似乎有很多问题。我会选择更简单的面向对象的pundit

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


【解决方案1】:

由于您提到的原因,太多未解决的问题和未解决的拉取请求,我不再在新项目中使用 CanCan。

您可能想看看 Ryan 的“Authorization From Scratch”RailsCasts。

您可能还会发现以下 sn-ps 代码很有用:

lib/错误/

module Errors
  class NotAuthorizedError < StandardError; end
end

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

  def authorize(record)
    raise Errors::NotAuthorizedError unless policy(record).public_send(params[:action] + "?")
  end

  def policy(record)
    "#{record.class}Policy".constantize.new(current_user, record)
  end
end

app/policies/user_policy.rb

class UserPolicy

  attr_reader :user, :current_user

  def initialize(current_user, user)
    @current_user = current_user
    @user = user
  end

  def update?
    user == current_user
  end
end

应用程序/控制器/

class UsersController

  def update
    @user = User.find(params[:id])
    authorize(@user)
    # etc
  end
end

我目前在所有新应用中使用的这个解决方案基于以下优秀文章:http://www.elabs.se/blog/52-simple-authorization-in-ruby-on-rails-apps。它的实现和测试非常简单,您可以轻松地将其调整为您的应用程序需求。

祝你好运取代 CanCan。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2018-01-18
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多