如何在角色模型中使用CanCan

zen*_*126 3 ruby roles ruby-on-rails cancan

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

我目前有一个Role带有字符串属性的User模型,以及一个来自设计的模型.我从哪里开始?

我已经看过这篇文章,但它没有完全解释如何设置角色以及角色模型和CanCan的ability.rb文件之间的关系.

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

编辑

我已经看过关于这个的railscast,它没有我想要的单独的Role模型.我尝试过使用Rolify,但人们说它太复杂了,而且可以用更简单的方式来实现.我也遇到了一些复杂问题,所以我想使用自己的角色模型.

编辑

我目前正在使用rolify并且角色正在运行.我找到了我的解决方案:https://github.com/EppO/rolify/wiki/Tutorial

Mat*_*ias 6

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

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
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

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

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

现在你应该知道如何使用cancan,角色和所有东西:-).