From 81625aba72c62305c10d9f3abb7ed7dd425d69f5 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 6 Jun 2022 14:24:05 -0500 Subject: [PATCH] Add Alphabetize Schema Columns To Keep Them Consistent as a Rails TIL --- README.md | 3 ++- ...-schema-columns-to-keep-them-consistent.md | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 rails/alphabetize-schema-columns-to-keep-them-consistent.md diff --git a/README.md b/README.md index bf87e18..3a73251 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). -_1220 TILs and counting..._ +_1221 TILs and counting..._ --- @@ -708,6 +708,7 @@ _1220 TILs and counting..._ - [Advance The Date](rails/advance-the-date.md) - [Allow List Params Anywhere With Strong Params](rails/allow-list-params-anywhere-with-strong-params.md) - [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md) +- [Alphabetize Schema Columns To Keep Them Consistent](rails/alphabetize-schema-columns-to-keep-them-consistent.md) - [Assert Two Arrays Have The Same Items With RSpec](rails/assert-two-arrays-have-the-same-items-with-rspec.md) - [Attach A File With Capybara](rails/attach-a-file-with-capybara.md) - [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md) diff --git a/rails/alphabetize-schema-columns-to-keep-them-consistent.md b/rails/alphabetize-schema-columns-to-keep-them-consistent.md new file mode 100644 index 0000000..358e005 --- /dev/null +++ b/rails/alphabetize-schema-columns-to-keep-them-consistent.md @@ -0,0 +1,25 @@ +# Alphabetize Schema Columns To Keep Them Consistent + +When working on a Rails project with a team, there can be lots of unnecessary +churn in the `db/schema.rb` file. While there are a couple things that can +cause this churn, the main one is reordering of columns during local migration. + +The [`strong_migrations` gem](https://github.com/ankane/strong_migrations) +provides [a handy rake task to apply alphabetical ordering to columns +names](https://github.com/ankane/strong_migrations#schema-sanity). This keeps +them in a consistent order which reduces churn. + +Assuming you have the `strong_migrations` gem included in your app, add the +following line to the end of your `Rakefile`. + +```ruby +task "db:schema:dump": "strong_migrations:alphabetize_columns" +``` + +This sets `strong_migrations:alphabetize_columns` as a prerequisite task to +`db:schema:dump`. Whenever `db:schema:dump` gets run, the alphabetization task +will get run first. This ensures the resulting `db/schema.rb` file always has +column names in a consistent order. + +The origin of this idea is Paul Gross's blog post [Alphabetize schema.rb +Columns](https://www.pgrs.net/2008/03/12/alphabetize-schema-rb-columns/).