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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With