Forked from jenheilemann/20130822132243_change_product_long_description.rb
Created
October 16, 2021 09:34
-
-
Save sadiqmmm/17750f5c9ef1a942538bea95683f23f3 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 hidden or 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment