File tree 2 files changed +36
-1
lines changed
2 files changed +36
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1235 TILs and counting..._
13
+ _ 1236 TILs and counting..._
14
14
15
15
---
16
16
@@ -788,6 +788,7 @@ _1235 TILs and counting..._
788
788
- [ Query A Single Value From The Database] ( rails/query-a-single-value-from-the-database.md )
789
789
- [ Read In Environment-Specific Config Values] ( rails/read-in-environment-specific-config-values.md )
790
790
- [ 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 )
791
792
- [ Remove The Default Value On A Column] ( rails/remove-the-default-value-on-a-column.md )
792
793
- [ Render An Alternative ActionMailer Template] ( rails/render-an-alternative-action-mailer-template.md )
793
794
- [ Render The Response Body In Controller Specs] ( rails/render-the-response-body-in-controller-specs.md )
Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments