From f394ecc0552fbac3a18546b80e1b893be2ca57fe Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 7 Jul 2022 11:43:15 -0500 Subject: [PATCH] Add Make Remove Column Migration Reversible as a Rails TIL --- README.md | 3 +- ...make-remove-column-migration-reversible.md | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 rails/make-remove-column-migration-reversible.md diff --git a/README.md b/README.md index 2c46192..8e5b48f 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1226 TILs and counting..._ +_1227 TILs and counting..._ --- @@ -767,6 +767,7 @@ _1226 TILs and counting..._ - [Log SQL Queries Executed By ActiveRecord](rails/log-sql-queries-executed-by-activerecord.md) - [Mark A Migration As Irreversible](rails/mark-a-migration-as-irreversible.md) - [Make ActionMailer Synchronous In Test](rails/make-action-mailer-synchronous-in-test.md) +- [Make Remove Column Migration Reversible](rails/make-remove-column-migration-reversible.md) - [Manually Run A Migration From Rails Console](rails/manually-run-a-migration-from-rails-console.md) - [Mark For Destruction](rails/mark-for-destruction.md) - [Mask An ActiveRecord Attribute](rails/mask-an-activerecord-attribute.md) diff --git a/rails/make-remove-column-migration-reversible.md b/rails/make-remove-column-migration-reversible.md new file mode 100644 index 0000000..c6e9bf7 --- /dev/null +++ b/rails/make-remove-column-migration-reversible.md @@ -0,0 +1,32 @@ +# Make Remove Column Migration Reversible + +The Rails migration DSL includes a +[`#remove_column`](https://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_column) +method for removing a column from a table. + +The two required values are the table name and the column name. + +```ruby +class RemoveNotesColumnFromTodo < ActiveRecord::Migration[5.2] + def change + remove_column :todos, :notes + end +end +``` + +This on it's own is not reversible though. If you were to run a `db:rollback` +with this migration, Rails wouldn't know what type to use when re-adding the +column. + +To make it reversible, you need to add in the column type as a third argument. + +```ruby + remove_column :todos, :notes, :string +``` + +Note: perhaps more importantly, this column isn't reversible in the sense that +when you remove the column, you are throwing away all the data associated with +that column. Be sure you're ready to part with this data before deploying a +migration like this. + +[source](https://stackoverflow.com/questions/24520550/how-do-you-make-remove-column-reversible)