ruby-on-rails - 如何将 CanCan 与角色模型一起使用

标签 ruby-on-rails ruby cancan roles

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

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

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

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

编辑

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

编辑

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

最佳答案

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

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

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

关于ruby-on-rails - 如何将 CanCan 与角色模型一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21211276/

相关文章:

ruby-on-rails - MiniTest 中的方法期望

ruby-on-rails - 在 ActiveRecord 模型中设置默认随机列值

ruby-on-rails - Postgres JSON Rails 查询

ruby-on-rails - 启动 Rails 服务器时出错 - 获取 "uninitialized constant Devise::Models::Invitable (NameError)"

ruby-on-rails - 康康的正确使用方式

ruby-on-rails - 使用 Devise 和 STI 设计具有多种用户类型的 Rails 应用程序

ruby - 在调用单例方法时动态创建方法作为参数

ruby - 用于 Ruby 或 Sinatra 应用程序的 pm2?

ruby-on-rails - CanCanCan 在哪里定义 flash "%{subject}",如何修改以符合 Rails 本地化约定?

ruby-on-rails - 在 Rails 应用程序上设计、CanCan 和 ActiveAdmin