diff --git a/README.md b/README.md index 9fe7060..34f309c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_533 TILs and counting..._ +_534 TILs and counting..._ --- @@ -342,6 +342,7 @@ _533 TILs and counting..._ - [Attribute Was](rails/attribute-was.md) - [Autosave False On ActiveRecord Associations](rails/autosave-false-on-activerecord-associations.md) - [Capybara Page Status Code](rails/capybara-page-status-code.md) +- [Change The Nullability Of A Column](rails/change-the-nullability-of-a-column.md) - [Code Statistics For An Application](rails/code-statistics-for-an-application.md) - [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md) - [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md) diff --git a/rails/change-the-nullability-of-a-column.md b/rails/change-the-nullability-of-a-column.md new file mode 100644 index 0000000..6d24177 --- /dev/null +++ b/rails/change-the-nullability-of-a-column.md @@ -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 +```