1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-08 09:38:04 +00:00

Add Change The Nullability Of A Column as a rails til

This commit is contained in:
jbranchaud
2017-06-02 00:08:46 -05:00
parent 8b1c3dacd6
commit 2402e56210
2 changed files with 30 additions and 1 deletions

View File

@@ -0,0 +1,28 @@
# Change The Nullability Of A Column
Do you have an existing table with a column that is exactly as you want it
except that it needs to be changed to either `null: false` or `null: true`?
One option is to use ActiveRecord's `change_column_null` method in your
migration.
For example to change a nullable column to `null: false`, you'll want a
migration like the following:
```ruby
def change
change_column_null :posts, :title, false
end
```
Note, if you have existing records with `null` values in the `title` column,
then you'll need to deal with those before migrating.
If you want to make an existing column nullable, change that `false` to
`true`:
```ruby
def change
change_column_null :posts, :title, true
end
```