The simplest Enum you will ever find for your ActiveRecord models
I have been using a really useful snippet for a while now.
While dropping it today into a project I realized just how powerful it is:
- it’s a drop-in and will work on any project
- it’s database agnostic
- it’s dead simple
- it’s not sensitive to enum changes
- and more and more
Just as an into, an enum is a way to have string represented as integers in your database.
Because integers are much faster to index and query (at least on mysql).
MySQL has an enum solution but ActiveRecord can’t really use it without some nasty hacking and it’s really messy when you want to add another param.
Enough Said, here’s the snippet
This gives you the ability to work with the Account model like so:
As you can see, it’s being persisted into the database as an integer, but you work with symbols/strings which is much nicer and cleaner.Submit to Hacker News
[NOTE] This post has been imported to Hugo from a Wordpress blog. It may be broken, missing images, code snippets or other information.
[NOTE] updated May 8, 2012. It's 2380 days old . This article may have outdated content.