Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if an ActiveRecord attribute is an Enum?

How would I test if an ActiveRecord attribute is an Enum? (as per Rails 4.1 enum declaration)

It's stored in the database and using the type method on columns_hash identifies the attribute as an integer.

Enum definition in model

enum status: [ :in_progress, :accepted, :approved, :declined, :closed, :cancelled, :submitted ]

To pull the type

irb(main):030:0> Application.columns_hash['status'].type
=> :integer
like image 637
Michael Glenn Avatar asked Jul 29 '14 21:07

Michael Glenn


1 Answers

ActiveRecord::Enum adds a defined_enums class attribute to the model - a hash storing the defined enums:

MyModel.defined_enums
#=> {"status"=>{"in_progress"=>0, "accepted"=>1, "approved"=>2, "declined"=>3, "closed"=>4, "cancelled"=>5, "submitted"=>6}}

To test if an attribute is an enum you could use:

MyModel.defined_enums.has_key?('status')
#=> true

Unfortunately, defined_enums is not documented.

like image 167
Stefan Avatar answered Oct 23 '22 05:10

Stefan