3

我可以通过以下方式轻松测试用户是否具有特定角色

if user.has_role? :admin

如何获取用户的角色名称?就像是

users = User.all
user.each{ |user|
  puts user.role or users.role_name  ?
}

用户模型

class User < ActiveRecord::Base
  rolify
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me ,:username,:first_name,:last_name
  # attr_accessible :title, :body
end

好榜样

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => :users_roles
  belongs_to :resource, :polymorphic => true
  attr_accessible :name,:id
  scopify
end
4

1 回答 1

7

您可以使用

user.roles.first.name
于 2013-06-14T04:50:03.550 回答