Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum in a Postgres database in Rails 3? [closed]

Tags:

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.

like image 844
B Seven Avatar asked Sep 07 '11 16:09

B Seven


People also ask

Does Postgres support enum?

PostgreSQL enum is the data type that was used in PostgreSQL to stored same type of values in column field, we can store same type of values using enum.

How do enums work in Postgres?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.

How does enum work in Rails?

An enum is an attribute where the values map to integers in the database and can be queried by name. Enums also give us the ability to change the state of the data very quickly. This makes it easy to use enums in Rails and saves a lot of time by providing dynamic methods.


1 Answers

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.)

like image 64
rdvdijk Avatar answered Sep 17 '22 09:09

rdvdijk