如何将 CanCan 与多个设计模型集成? [英] How to integrate CanCan with multiple devise models?

查看:9
本文介绍了如何将 CanCan 与多个设计模型集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何为多个设计模型定义能力?

How would I go about defining abilities for several devise models?

推荐答案

让我们假设您的应用程序有两个独立的 Devise 驱动的用户模型,称为 UserAdmin.这意味着您可以同时使用 current_usercurrent_admin 之类的方法.

Let's assume your app has two separate Devise-powered user models called User and Admin. This means you use methods like current_user and current_admin side by side.

让我们进一步假设您只有/想要一个 Ability 类,其中包含您所有的 CanCan 权限设置...

Let's further assume that you only have/want a single Ability class, which contains all your CanCan permission settings...

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    case user
    when User
      can :create, Comment
      can :read, :all
    when Admin
      can :manage, :all
    end
  end
end

这正是其他人提出的建议,但您还需要采取另一个步骤.

This is exactly what others have proposed, but there's another step you have to take.

默认情况下,CanCan 假定方法 current_user 存在并将返回一个 User 对象以与您的 Ability 设置进行比较.但是,可以使用 current_admin 找到我们的管理员用户.不告诉 CanCan 在哪里可以找到管理对象,它们永远不会被审查,因此永远不会获得权限;在与管理员打交道时,我们必须更改默认设置.

By default, CanCan assumes that the method current_user exists and will return a User object to compare with your Ability settings. However, our admin users can be found using current_admin. Without telling CanCan where to find admin objects, they never get reviewed, and thus never get permissions; we must change the defaults when dealing with an admin.

将以下内容添加到 application_controller.rb...

Add the following to application_controller.rb...

def current_ability
  if admin_signed_in?
    @current_ability ||= Ability.new(current_admin)
  else
    @current_ability ||= Ability.new(current_user)
  end
end

现在我们的 Ability 类将查看 Admin 对象(如果有),并在不存在时回退到普通用户.

Now our Ability class will look at the Admin object if one is available, and fall back on a normal User when none is present.

进一步的开发允许我们将管理员权限移动到他们自己单独的能力类中...

Further development allows us to move Admin permissions into their own separate Ability class...

def current_ability
  if admin_signed_in?
    @current_ability ||= AdminPowers.new(current_admin)
  else
    @current_ability ||= Ability.new(current_user)
  end
end

有关详细信息,请参阅 Wiki 中的更改默认值.感谢 Stefan 为我指出正确的文章.

For more info, see Changing Defaults in the Wiki. Kudos to Stefan for pointing me at the proper article.

仅供参考 -- CanCan 已死,万岁CanCanCan日期与错误修复和新功能.相同的命名空间,因此它只是 Gemfile 中的一个替代 gem.

FYI -- CanCan is dead, long live CanCanCan! Up to date with bug fixes and new features. Same namespaces, so it's just a drop-in gem replacement in your Gemfile.

gem 'cancancan', '~> 1.8'

这篇关于如何将 CanCan 与多个设计模型集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆