【问题标题】:How to Use CanCan with Role Model如何将 CanCan 与角色模型一起使用
【发布时间】:2014-02-08 06:45:15
【问题描述】:

我正在使用 CanCan,并且一直在研究如何开始。但是,似乎大多数教程都不是很具体,也不适合我自己的需要。我正在构建一个社交网络,用户可以在其中创建项目并将其他用户添加到他们的项目中,从而允许这些用户管理该项目。

我目前有一个带有字符串属性的Role 模型和一个来自devise 的User 模型。我从这里去哪里?

我看过this post,但它并没有完全解释如何设置角色以及角色模型与CanCan的ability.rb文件之间的关系。

如果您需要我说得更具体,请说出来!我不是最伟大的 Rails 开发者;)

编辑

我已经看过关于此的 railscast,它没有我想要的单独的角色模型。我尝试过使用 Rolify,但人们说它太复杂了,可以用更简单的方式来做。我也遇到了一些并发症,所以我只想使用我自己的角色模型。

编辑

我目前正在使用 rolify,并且这些角色正在发挥作用。我在以下位置找到了我的解决方案:https://github.com/EppO/rolify/wiki/Tutorial

【问题讨论】:

  • 在能够提供任何有用的答案之前,我们确实需要更多地了解您正在尝试做的事情。也许首先描述UserRole 模型以及它们如何与您尝试进行身份验证的其他模型交互。

标签: ruby-on-rails ruby cancan roles


【解决方案1】:

如果您的用户角色内容类似于以下内容:

class User < ActiveRecord::Base
  has_many :user_roles
  has_many :roles, :through => :user_roles

  # user model has for example following attributes:
  # username, email, password, ...
end

class Role < ActiveRecord::Base
  has_many :user_roles
  has_many :users, :through => :user_roles

  # role model has for example following attributes:
  # name (e.g. Role.first.name => "admin" or "editor" or "whatever"
end

class UserRole < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

您可以执行以下操作:

首先,使用一些辅助方法或类似方法扩展您的用户模型:

class User < ActiveRecord::Base

  def is_admin?
    is_type?("admin")
  end

  def is_editor?
    is_type?("editor")
  end

  def is_whatever?
    is_type?("whatever")
  end

  private

  def is_type? type
    self.roles.map(&:name).include?(type) ? true : false # will return true if the param type is included in the user´s role´s names. 
  end

end

第二,扩展你的能力等级:

class Ability
  include CanCan::Ability

  def initialize(user)
    if user
      can :manage, :all if user.is_admin?
      can :create, Project if user.is_editor?
      can :read, Project if user.is_whatever?
      # .. and so on..
      # you can work with your different roles on base of the given user instance.
    end
  end
end

或者,您可以删除您的 User-Roles has-many-through 关联并将其替换为 easy-roles gem - 非常有用。可以在 github 上找到:https://github.com/platform45/easy_roles

现在您应该知道如何将 cancan、角色和所有东西一起使用 :-)。

【讨论】:

  • 非常感谢您的回复。我使用了 rolify 而不是 easy-roles,但它们的作用几乎相同!
  • 答案有用/解决方案吗?如果是,你可以接受;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多