Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails 4.2, how do I convert an integer to an enum?

In Rails 4.2 I can write:

class Task < ActiveRecord::Base
  enum priority: { normal: 50, low: 0, high: 100 }
end

If I have a SQL query which (for obscure reasons) returns the priority as an integer, is there a simple way to convert that integer into its corresponding enumerated value, eg. :high?

(Obviously I can look up the key from the value in Task.priorities, or define my own reverse index, but presumably this is already implemented somewhere in Rails...)

like image 864
MZB Avatar asked Mar 09 '15 17:03

MZB


1 Answers

Apparently in ruby 1.9+ I can write:

Task.priorities.key(100)
=> "high"

No idea if this is efficient, but since the hash table is small...

like image 153
MZB Avatar answered Sep 19 '22 03:09

MZB