From cafb9994250c3f53b65cd6f5af0989320208ab6d Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 26 Mar 2020 15:10:02 -0500 Subject: [PATCH] Add Write Reversible Migration To Set Default as a rails til --- README.md | 3 +- ...ite-reversible-migration-to-set-default.md | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 rails/write-reversible-migration-to-set-default.md diff --git a/README.md b/README.md index bef048a..d1e7282 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_905 TILs and counting..._ +_906 TILs and counting..._ --- @@ -584,6 +584,7 @@ _905 TILs and counting..._ - [Upgrading Your Manifest For Sprocket's 4](rails/upgrading-your-manifest-for-sprockets-4.md) - [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md) - [Wipe Out All Precompiled Assets](rails/wipe-out-all-precompiled-assets.md) +- [Write Reversible Migration To Set Default](rails/write-reversible-migration-to-set-default.md) - [Write Safer Where Clauses With Placeholders](rails/write-safer-where-clauses-with-placeholders.md) ### React diff --git a/rails/write-reversible-migration-to-set-default.md b/rails/write-reversible-migration-to-set-default.md new file mode 100644 index 0000000..e59a1b0 --- /dev/null +++ b/rails/write-reversible-migration-to-set-default.md @@ -0,0 +1,29 @@ +# Write Reversible Migration To Set Default + +You can use the `change_column_default` method to alter the default value of a +column. If the column doesn't have a default, then you'd essentially be +changing the default from `nil` to _some value_. + +```ruby +def up + change_column_default :books, :published, false +end + +def down + change_column_default :books, :published, nil +end +``` + +This is fine, but you can write the migration as a single, reversible `change` +method using the `:from` and `:to` options. + +```ruby +def change + change_column_default :books, :published, from: nil, to: false +end +``` + +When you migrate, the default will be set to `false`. When you rollback, the +default will be removed. + +[source](https://blog.arkency.com/how-to-add-a-default-value-to-an-existing-column-in-a-rails-migration/)