Skip to content
Browse files

Migration given some actual code

  • Loading branch information...
1 parent b47dc76 commit 3a56439ce5cf041d7e8ab1fa811270bf34e77116 @pat pat committed
Showing with 25 additions and 0 deletions.
  1. +25 −0 db/migrate/20080929074602_switch_states.rb
View
25 db/migrate/20080929074602_switch_states.rb
@@ -1,7 +1,32 @@
class SwitchStates < ActiveRecord::Migration
def self.up
+ select_values(
+ "SELECT DISTINCT state FROM contacts"
+ ).each do |state|
+ State.create :name => state
+ end
+
+ add_column :contacts, :state_id, :integer
+ add_index :contacts, :state_id
+
+ Contact.find(:all).each do |contact|
+ contact.update_attributes(
+ :state_id => State.find_by_name(contact.attributes["state"]).id
+ )
+ end
+
+ remove_column :contacts, :state
end
def self.down
+ add_column :contacts, :state, :string
+
+ Contact.find(:all).each do |contact|
+ execute "UPDATE contacts SET state = '#{contact.state.name}' WHERE id = #{contact.id}"
+ end
+
+ remove_column :contacts, :state_id
+
+ State.find(:all).each { |state| state.destroy }
end
end

0 comments on commit 3a56439

Please sign in to comment.
Something went wrong with that request. Please try again.