67

How do I describe an enumeration column in a Rails 3 migration?

Alex Antonov
  • 14,134
  • 7
  • 65
  • 142
Zeck
  • 6,433
  • 21
  • 71
  • 111

11 Answers11

73

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.

Alex Antonov
  • 14,134
  • 7
  • 65
  • 142
9

In a Rails 3 Migration you can do the following:

class CreateFoo < ActiveRecord::Migration
  def change
    create_table :foo do |t|
      t.column :foobar, "ENUM('foo', 'bar')"
    end
  end
end

This will create the table with the single column "foobar" and the values.

amerdidit
  • 91
  • 1
  • 1
5

You can describe an enumeration column with:

t.column 'role', 'user_role'

I created the enum type with:

execute "CREATE TYPE user_role AS ENUM ('consultant', 'admin');"

Inspecting the database:

    Column     |          Type          | Modifiers | Storage  | Stats target | Description
---------------+------------------------+-----------+----------+--------------+-------------
 role          | user_role              |           | plain    |              |
Moriarty
  • 3,957
  • 1
  • 31
  • 27
3

This will also work....

add_column :table_name, :column_name, "enum('abc','def','ghi')", :default => 'abc'

bigtex777
  • 1,150
  • 10
  • 15
3

Something like

class User < ActiveRecord::Base
   validates_inclusion_of :status, :in => [:active, :inactive]

   def status
     read_attribute(:status).to_sym
   end

   def status= (value)
     write_attribute(:status, value.to_s)
   end
 end
ceth
  • 44,198
  • 62
  • 180
  • 289
3

I like enumerated_attribute gem: https://github.com/jeffp/enumerated_attribute

Easy enum for your models, objects and views.

Works fine with rails 3.1

1

What worked for me was mapping it from symbols to integers

TYPE_MAP = { type_one: 1, type_two:2, another_type:3 }

def type
    TYPE_MAP.key(read_attribute(:type))
end

def type=(s)
    write_attribute(:type, TYPE_MAP[s])
end

But for the controller you have to map it again like this:

 def create
  @cupon_type = CuponType.new(params[:cupon_type])
  @cupon_type.type = params[:cupon_type][:type].to_sym

Note the .to_sym that overrides the first creation on the object (in my case it was coupons).

Now you can use it like this:

c.type == :type_one
c.type = :type_two
DanielZiv
  • 107
  • 8
1

I'll use the enum_fu gem: https://github.com/ikspres/enum_fu

Pasta
  • 1,750
  • 2
  • 14
  • 25
0

Have a look at active_enum.

I think it fits your needs.

Pikachu
  • 774
  • 13
  • 15
0

Use enum_column to add enum support to active record

https://github.com/mdsol/enum_column

Mohsen Alizadeh
  • 1,595
  • 12
  • 25
-3
t.enum :file_type ,:limit => [:jpg, :png, :gif] ,:default => :gif
HeeL
  • 295
  • 1
  • 2
  • 8