Created
August 22, 2013 14:39
-
-
Save jenheilemann/6308068 to your computer and use it in GitHub Desktop.
Rails migrations: String to Text and back again. It's kind of complicated to update a database column that is currently a "string" and convert it into "text." Well, it's not hard to update the column, but it can be dangerous if you need to rollback the migration - Postgresql and other databases don't like adding a limit to the column, and the `r…
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 ChangeProductLongDescription < ActiveRecord::Migration | |
def up | |
# simple and straightforward | |
change_column :products, :long_description, :text | |
end | |
# but why cant it just be: | |
# change_column :product, :long_description, :string | |
# ??? | |
# because effin databases don't like you, that's why. | |
def down | |
# create a temporary column to hold the truncated values | |
# we'll rename this later to the original column name | |
add_column :products, :temp_description, :string | |
# use #find_each to load only part of the table into memory | |
Product.find_each do |product| | |
temp_description = product.long_description | |
# test if the new value will fit into the truncated field | |
if product.long_description.length > 255 | |
temp_description = product.long_description[0,254] | |
end | |
# use #update_column because it skips validations AND callbacks | |
product.update_column(:temp_description, temp_description) | |
end | |
# delete the old column since we have all the data safe in the | |
# temp_description | |
remove_column :products, :long_description | |
# rename the temp_column to our original column name | |
rename_column :products, :temp_description, :long_description | |
end | |
end |
Thanks for sharing!
I ran into one issue where long_description
can be nil
in my database, so I needed to change L22 to
if product.long_description && product.long_description.length > 255
Very helpful! 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It worked perfectly when doing a rollback, thanks for sharing!