Rails 4 enum - how to check equality?

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 only want to do something if my user is - :domain_adminand I use the following test:

if @user.role == :domain_admin

The test returns false when @user.role(in the console) returns :domain_admin. Thus, the value is set correctly, but I must be mistaken, checking its equality, or the listing does not work, as I thought before. I assumed that I read the documentation that they were thin (small).

Can someone tell me how I am testing equality for :domain_adminas well as how to test >= :domain_admin?

Many thanks.

+4
1
@user.domain_admin? # return true if :domain_admin

:

@user.role == :domain_admin

:

@user.role == "domain_admin"

:

=> 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
+5

Source: https://habr.com/ru/post/1539745/


All Articles