Created
May 17, 2012 15:10
-
-
Save patakijv/2719545 to your computer and use it in GitHub Desktop.
rails string to boolean migration while preserving existing data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ChangeIgnoredToBoolean < ActiveRecord::Migration | |
# we should have been using boolean vs string for a flag instead of a string | |
def up | |
# preserve existing data | |
@saved_ignored_state = Message.all.map(&:ignored) | |
change_column(:messages, :ignored, :boolean, :default => false) | |
Message.reset_column_information | |
Message.all.each_with_index do |message,index| | |
message.update_attribute(:ignored,@saved_ignored_state[index] == 'true') | |
end | |
end | |
def down | |
# preserve existing data | |
@saved_ignored_state = Message.all.map(&:ignored) | |
change_column(:messages, :ignored, :string, :default => 'false') | |
Message.reset_column_information | |
Message.all.each_with_index do |message,index| | |
message.update_attribute(:ignored,@saved_ignored_state[index] == true ? 'true' : 'false') | |
end | |
end | |
end |
Alternative way
class ChangeIgnoredToBoolean < ActiveRecord::Migration
def self.up
execute "ALTER TABLE messages ALTER COLUMN ignored DROP DEFAULT"
change_column :messages, :ignored, "boolean USING ignored != 'false'"
change_column_default :messages, :ignored, false
end
def self.down
execute "ALTER TABLE messages ALTER COLUMN ignored DROP DEFAULT"
change_column :messages, :taxation, "varchar(255) using case when ignored then 'true' else 'false' end"
change_column_default :messages, :ignored, 'false'
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, thanks, this was really useful!