Skip to content

Commit cafb999

Browse files
committed
Add Write Reversible Migration To Set Default as a rails til
1 parent 5a720a6 commit cafb999

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_905 TILs and counting..._
12+
_906 TILs and counting..._
1313

1414
---
1515

@@ -584,6 +584,7 @@ _905 TILs and counting..._
584584
- [Upgrading Your Manifest For Sprocket's 4](rails/upgrading-your-manifest-for-sprockets-4.md)
585585
- [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md)
586586
- [Wipe Out All Precompiled Assets](rails/wipe-out-all-precompiled-assets.md)
587+
- [Write Reversible Migration To Set Default](rails/write-reversible-migration-to-set-default.md)
587588
- [Write Safer Where Clauses With Placeholders](rails/write-safer-where-clauses-with-placeholders.md)
588589

589590
### React
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Write Reversible Migration To Set Default
2+
3+
You can use the `change_column_default` method to alter the default value of a
4+
column. If the column doesn't have a default, then you'd essentially be
5+
changing the default from `nil` to _some value_.
6+
7+
```ruby
8+
def up
9+
change_column_default :books, :published, false
10+
end
11+
12+
def down
13+
change_column_default :books, :published, nil
14+
end
15+
```
16+
17+
This is fine, but you can write the migration as a single, reversible `change`
18+
method using the `:from` and `:to` options.
19+
20+
```ruby
21+
def change
22+
change_column_default :books, :published, from: nil, to: false
23+
end
24+
```
25+
26+
When you migrate, the default will be set to `false`. When you rollback, the
27+
default will be removed.
28+
29+
[source](https://blog.arkency.com/how-to-add-a-default-value-to-an-existing-column-in-a-rails-migration/)

0 commit comments

Comments
 (0)