How to use enum in a Postgres database in Rails 3?

B Seven picture B Seven · Sep 7, 2011 · Viewed 7.2k times · Source

PostgreSQL has the concept of enumerated types built into the database.

How would you implement a table with a column that uses an enumerated type in Rails 3? Do you need to define the enum in PostgreSQL somehow? How could you create a DB migration that does this?

Working in Rails 3.07, Ruby 1.92p180, PostgreSQL 8.3.

Answer

rdvdijk picture rdvdijk · Sep 25, 2011

Rails does not support the ENUM datatype out of the box. This is because not all databases support it that datatype. I found that a common way of dealing with ENUM values is to manually create the enum column in your database (PostgreSQL in your case), and deal with it as a string column in your Rails application. Then, use the validates_inclusion_of validator to force the use of the allowed values.

validates_inclusion_of :gender, :in => [ "male", "female" ]

And use native SQL in your migration to add the enum field:

class AddEnumType < ActiveRecord::Migration
  def up
    execute ".." # your native PostgreSQL queries to add the ENUM field
  end
end

edit (June 2014)

Rails 4.1 now supports enums. The validates_inclusion_of can now be changed to:

enum gender: [ :male, :female ]

(However, this is still not natively supported by the underlying database, so the native SQL migration is still needed.)