Skip to content

Commit e5166f2

Browse files
committed
Add Remove A Database Column From A Table as a Rails TIL
1 parent 423b354 commit e5166f2

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1235 TILs and counting..._
13+
_1236 TILs and counting..._
1414

1515
---
1616

@@ -788,6 +788,7 @@ _1235 TILs and counting..._
788788
- [Query A Single Value From The Database](rails/query-a-single-value-from-the-database.md)
789789
- [Read In Environment-Specific Config Values](rails/read-in-environment-specific-config-values.md)
790790
- [Read-Only Models](rails/read-only-models.md)
791+
- [Remove A Database Column From A Table](rails/remove-a-database-column-from-a-table.md)
791792
- [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md)
792793
- [Render An Alternative ActionMailer Template](rails/render-an-alternative-action-mailer-template.md)
793794
- [Render The Response Body In Controller Specs](rails/render-the-response-body-in-controller-specs.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Remove A Database Column From A Table
2+
3+
The `ActiveRecord` migration DSL includes a method
4+
[`remove_column`](https://api.rubyonrails.org/v7.0.3.1/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_column)
5+
that can be used to remove an existing column from a table.
6+
7+
It can be used like so, to remove the `sign_in_count` column from the `users`
8+
table.
9+
10+
```ruby
11+
def change
12+
remove_column :users, :sign_in_count
13+
end
14+
```
15+
16+
Though that will work fine, you'll run into an `IrreversibleMigration` error if
17+
you try to `rails db:rollback`. It usually a good bet to make migrations
18+
reversible when it is easy to do so.
19+
20+
All we need in order to make this migration reversible is to add the column
21+
type.
22+
23+
```ruby
24+
def change
25+
remove_column :users, :sign_in_count, :integer
26+
end
27+
```
28+
29+
Now you can rollback (or [migrate up-down-up](migrating-up-down-up.md)) no
30+
problem.
31+
32+
Keep in mind that only the structural changes are reversible. When you remove
33+
the column, all of the data goes with it, and that cannot be undone with a
34+
simple rollback.

0 commit comments

Comments
 (0)