Question

I am using Rails 4.1 and Ruby 2.1.1

I have a line in my user model:

enum role: [:user, :admin, :team_admin, :domain_admin, :super_admin]

In my controller I want to only do something if my user is a :domain_admin and I use the following test:

if @user.role == :domain_admin

The test returns false when @user.role (in the console) returns :domain_admin. So the value is set properly, but I must be misunderstanding testing equality of it, or enum's do not work as I previously thought. I assumed from reading the documentation that they were a thin layer over (small) ints.

Could anyone tell me how I test equality for :domain_admin, and also how do I test >= :domain_admin?

Many thanks.

Était-ce utile?

La solution

@user.domain_admin? # return true if :domain_admin

instead:

@user.role == :domain_admin

use:

@user.role == "domain_admin"

Some test:

=> User.roles
=> {"user"=>0, "staff"=>1, "admin"=>2}
=> u = User.last
=> u.role
=> "user"
=> u.role == "user" # <-- this 
=> true
=> User.roles.each_pair { |x, _| puts u.role == x }
=> true
=> false
=> false
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top