本文介绍了如何使用cancancan?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给我的Rails应用程序权限的用户。我有'管理员'谁可以创建,更新和删除所有文章和评论,用户谁可以创建和更新只是他自己的意见,和'客人',谁可以做所有这些。为此,我用宝石色器件和cancancan。我理解的色器件的宝石,但我不明白'cancancan。

I want to give rights to users in my rails app. I have 'admin' who can create, update and delete all posts and comments, 'user' who can create and update only his own comments, and 'guest' who can do none of these. For this I use the gems 'devise' and 'cancancan'. I understand the 'devise' gem, but I don't understand 'cancancan'.

在类ability.rb,我怎么能写为这些用户(管理员,用户,客人)?

In the class ability.rb, how can I write rights for these users (admin, user, guest)?

推荐答案

Cancancan 让你只定义了特定环境下的权限。这方面可能是它不是一部分的用户角色 cancancan ,因此角色必须由你自己来定义。

Cancancan lets you only define permissions for given context. This context might be a user role which is not a part of cancancan and hence roles have to be defined by yourself.

有多种方式来定义用户角色,例如

There are various ways to define user role, e.g.


  • 角色模式,


  • 的建议,

  • 用户模型的字符串属性。

  • as a Role model,
  • Rails enum,
  • as suggested here,
  • as a string attribute of User model.

这一切都取决于使用情况。如何界定能力的例子可以发现。对你来说,它看起来像:

It all depends of the use case. An example of how to define abilities can be found here. In your case, it would look like:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.reviewer? #Just a logged user
      can :manage, Comment, { owner_id: user.id }
    elsif user.admin?
      can :manage, :all
    end
  end
end

class User < ActiveRecord::Base
  enum role: [ :reviewer, :admin ]
end

这篇关于如何使用cancancan?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 11:05