Today I Learned

hashrocket A Hashrocket project

ActiveRecord List All Enums

Today I learned a way to view all the enums defined on an ActiveRecord Model.

Suppose I have a class Post with enums status and category:

class Post < ApplicationRecord
  enum status: [:draft, :published]
  enum category: [:ruby, :rails, :lord_of_the_rings]
end

I can view the enum values for statuses with Post.statuses and category with Post.categories, but what if I want to see all the enums on Post? defined_enums will do that:

Post.defined_enums
# => {"status"=>{"draft"=>0, "published"=>1}, "category"=>{"ruby"=>0, "rails"=>1, "lord_of_the_rings"=>2}}

You can of course key in to each enum here too:

Post.defined_enums["status"]
# => {"draft"=>0, "published"=>1}
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.