Skip to content

Instantly share code, notes, and snippets.

@patakijv
Created May 17, 2012 15:10
Show Gist options
  • Save patakijv/2719545 to your computer and use it in GitHub Desktop.
Save patakijv/2719545 to your computer and use it in GitHub Desktop.
rails string to boolean migration while preserving existing data
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
@bruno-
Copy link

bruno- commented Mar 12, 2013

Hey, thanks, this was really useful!

@Supro
Copy link

Supro commented Aug 20, 2015

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