enum, , , , , " />

Enumeration Columns with Rails

March 18, 2009

toolboxOne of the many database features hated by Rails is enumerated columns. Even if you add them to your migration by dirtying your hands with SQL yourself, then the schemadumper interprets them as zero length strings as mentioned in Rob Sanheim’s blog. Funtime!

I however like enumerated columns because they save space and are pretty, and so I wrote a short and sweet migration_enum plugin to help me out. However, so be the fate of the web dev that someone else has already written a better one.

The solution is the Enumerated Columns by William Sobel. He even added support for radio buttons in your views!

t.column :severity, :enum, :limit => [:low, :medium, :high, :critical]

The one thing I dislike is that my “legacy” system which has been using enumerated columns interprets them as strings all over the place in the rails code. Enumerated Columns plugins treats them as symbols and breaks me. To fix, I wrote a little patch.

So to get it all:

script/plugin install svn://rubyforge.org/var/svn/enum-column/plugins/enum-column
cd vendor/plugins/enum-columm
curl http://snowgiraffe.com/downloads/rails/enum_patch.diff > enum_patch.diff
patch -p0 < enum_patch.diff

In environment.rb (or an initializer) add:

ActiveRecordEnumerations::Column.use_strings = true

Leave a Reply