diff --git a/README.md b/README.md index 6c27ecc..3a60ae6 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). -_1235 TILs and counting..._ +_1236 TILs and counting..._ --- @@ -788,6 +788,7 @@ _1235 TILs and counting..._ - [Query A Single Value From The Database](rails/query-a-single-value-from-the-database.md) - [Read In Environment-Specific Config Values](rails/read-in-environment-specific-config-values.md) - [Read-Only Models](rails/read-only-models.md) +- [Remove A Database Column From A Table](rails/remove-a-database-column-from-a-table.md) - [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md) - [Render An Alternative ActionMailer Template](rails/render-an-alternative-action-mailer-template.md) - [Render The Response Body In Controller Specs](rails/render-the-response-body-in-controller-specs.md) diff --git a/rails/remove-a-database-column-from-a-table.md b/rails/remove-a-database-column-from-a-table.md new file mode 100644 index 0000000..cc46344 --- /dev/null +++ b/rails/remove-a-database-column-from-a-table.md @@ -0,0 +1,34 @@ +# Remove A Database Column From A Table + +The `ActiveRecord` migration DSL includes a method +[`remove_column`](https://api.rubyonrails.org/v7.0.3.1/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_column) +that can be used to remove an existing column from a table. + +It can be used like so, to remove the `sign_in_count` column from the `users` +table. + +```ruby +def change + remove_column :users, :sign_in_count +end +``` + +Though that will work fine, you'll run into an `IrreversibleMigration` error if +you try to `rails db:rollback`. It usually a good bet to make migrations +reversible when it is easy to do so. + +All we need in order to make this migration reversible is to add the column +type. + +```ruby +def change + remove_column :users, :sign_in_count, :integer +end +``` + +Now you can rollback (or [migrate up-down-up](migrating-up-down-up.md)) no +problem. + +Keep in mind that only the structural changes are reversible. When you remove +the column, all of the data goes with it, and that cannot be undone with a +simple rollback.