سؤال

I can easily to test if a user has certain role by

if user.has_role? :admin

How do I get a user's role name? Something like

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

User model

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

role model

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
هل كانت مفيدة؟

المحلول

you can use

user.roles.first.name
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top