康康宝石简单问题

发布于 2024-10-19 23:58:14 字数 666 浏览 1 评论 0原文

models/ability.rb

class Ability
  include CanCan::Ability

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

    if user.role? :admin
      can :manage, :all
    else
      can :read, :all
      can :create, Comment
      can :update, Comment do |comment|
        comment.try(:user) == user || user.role?(:moderator)
      end
      if user.role?(:author)
        can :create, Article
        can :update, Article do |article|
          article.try(:user) == user
        end
      end
    end
  end
end

在 Railscasts 中有方法 user.role? :管理员和if user.role?(:author).我不明白。我是否需要在模型中创建一个方法才能使其工作?

我将角色存储在用户表中作为角色列。

models/ability.rb

class Ability
  include CanCan::Ability

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

    if user.role? :admin
      can :manage, :all
    else
      can :read, :all
      can :create, Comment
      can :update, Comment do |comment|
        comment.try(:user) == user || user.role?(:moderator)
      end
      if user.role?(:author)
        can :create, Article
        can :update, Article do |article|
          article.try(:user) == user
        end
      end
    end
  end
end

In Railscasts there are methods user.role? :admin & if user.role?(:author).I dont get it. Do i need to create a method in model to make it work?

I'm storing roles in Users table as a role column.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风和你 2024-10-26 23:58:14

是的,你需要自己写这个。不过,CanCan 项目有一个 wiki 页面描述如何执行此操作

维基百科的第一行说:

“CanCan 与您的方式脱钩
在用户模型中实现角色,但是
如何建立基于角色的基本
授权?”

我几乎完全不同意该页面上使用 role_mask 的示例,但该页面仍然很好,应该给您一些想法。

还有 单独的角色模型示例,我个人更喜欢它。这取决于你想将角色存储在哪里信息。

Yes, you need to write this yourself. However, the CanCan project has a wiki page describing how to do this.

The first line of the wiki says:

"CanCan is decoupled from how you
implement roles in the User model, but
how might one set up basic role-based
authorization?"

Note that I disagree almost completely with the example on that page that uses a role_mask, but the page is still good and should give you some ideas.

There is also the Separate Role Model example, which I personally like better. It depends on where you want to store your role information.

翻身的咸鱼 2024-10-26 23:58:14

如果您正在寻找即插即用的 gem,那么请查看声明性授权。
Raynb 说他开发 Cancan 是因为 DA 对于这里的某些项目来说太过分了:http: //railscasts.com/episodes/192-authorization-with-cancan?autoplay=true

If you're looking for a gem that is plug-and-play, then check out Declarative Authorization.
Raynb says that he developed Cancan because DA was overkill for some projects here: http://railscasts.com/episodes/192-authorization-with-cancan?autoplay=true

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文