Skip to content

Instantly share code, notes, and snippets.

@bxt
Created February 2, 2015 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxt/bdb29034b9ed14324614 to your computer and use it in GitHub Desktop.
Save bxt/bdb29034b9ed14324614 to your computer and use it in GitHub Desktop.
class SwitchTypeOfStateToEnum < ActiveRecord::Migration
class Order < ActiveRecord::Base
enum state: [ :pending, :running, :success, :failed ]
end
def change
rename_column :orders, :state, :state_old
add_column :orders, :state, :integer
reversible do |dir|
dir.up do
say_with_time 'Writing values into the new enum state column' do
Order.all.each do |t|
t.state = t.state_old
t.save!
end.size
end
end
dir.down do
say_with_time 'Writing values from enum back into the old state column' do
Order.all.each do |t|
t.state_old = t.state.to_s
t.save!
end.size
end
end
end
remove_column :orders, :state_old, :string
end
end

Sample Migration for Rails 4.1 Enums

Rails 4.1 added enums to Active Record adding some convenient access and manipulation helpers for the typical status field. If you want to start using these in your legacy app today, you will not only have to update your models accordingly and add enum declarations, but you might also want to update your database schema and the contents of your production databases. This migration was written for just that usecase and schould be usable for your models and database with just some slight changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment