15
votes

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
2

2 Answers

29
votes

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.

-1
votes

I kept on finding this answer when trying to figure out how to do this, but @stefan's method was giving me an uninitialized constant PostsHelper::Application

Found this also works:

Post.type_for_attribute(attribute).is_a

Possibly a bit cleaner, since you don't have to worry about _prefix and _suffix?