How do I describe an enumeration column in a Rails 3 migration?
In Ruby on Rails, an enum is an attribute where the values map to integers in the database and can be queried by name. For example, we could define an enum for the status attribute, where the possible values are pending , active , or archived . Ruby on Rails added support for enums in Rails 4.1.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Every time a migration is generated using the rails g migration command, Rails generates the migration file with a unique timestamp. The timestamp is in the format YYYYMMDDHHMMSS . Whenever a migration is run, Rails inserts the migration timestamp into an internal table schema_migrations .
In MySQL one can create an enum as such: USE WorldofWarcraft; CREATE TABLE [users] ( ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, username varchar(255), password varchar(255), mail varchar (255), rank ENUM ('Fresh meat', 'Intern','Janitor','Lieutenant','Supreme being')DEFAULT 'Fresh meat', );
Rails 4.1 contains enum for now!
You can write just
class User < ActiveRecord::Base enum status: [ :admin, :user, :banned ] end
For migration write
t.integer :status
Rails 3 & 4.0
Best solution in my opinion is simple_enum gem.
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