ruby - can not find the user has a role of admin -


now try find whether user has permissions admin.

this user model code:

class user < activerecord::base   # include default devise modules. others available are:   # :token_authenticatable, :confirmable,   # :lockable, :timeoutable , :omniauthable   devise :database_authenticatable, :registerable,          :recoverable, :rememberable, :trackable, :validatable    # setup accessible (or protected) attributes model   attr_accessible :email, :password, :password_confirmation, :remember_me   # attr_accessible :title, :body     has_many :user_roles   has_many :roles, :through => :user_roles     def has_role?(role)      case role         when :admin admin?         when :member true         else false      end   end    def admin?     roles.each |role|        return true if role.name == 'admin'     end      return false   end end 

now there user has role name = admin , test code here:

command:rails c

user  = user.find(1) user.has_role?('admin') 

result :

=> false

why not true?

what more think admin? method needs refactoring.now augly don`t know how refactor ):

it's because of use string in method argument , symbol in case statement.

it may better refactor has_role? method this:

def has_role?(role)   case role.to_s     when 'admin' admin?     when 'member' true     else false   end end 

.to_s used convert non-strings (such symbols) strings, may call has_role? :admin , has_role? 'admin' equal result.

also, admin? method looks ugly.

you may rewrite equally to:

def admin?   roles.any? { |r| r.name == 'admin' } end 

or write more generic has_role? as:

def has_role?(role)   roles.any? { |r| r.name == role.to_s } end 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -