1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-04 23:58:01 +00:00

Add Check If Any Records Have A Null Value as a rails til

This commit is contained in:
jbranchaud
2021-03-06 20:54:18 -06:00
parent 30af691b1b
commit 10972e4192
2 changed files with 29 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_1074 TILs and counting..._
_1075 TILs and counting..._
---
@@ -645,6 +645,7 @@ _1074 TILs and counting..._
- [Change The Nullability Of A Column](rails/change-the-nullability-of-a-column.md)
- [Change The Time Zone Offset Of A DateTime Object](rails/change-the-time-zone-offset-of-a-datetime-object.md)
- [Check If ActiveRecord Update Fails](rails/check-if-activerecord-update-fails.md)
- [Check If Any Records Have A Null Value](rails/check-if-any-records-have-a-null-value.md)
- [Check Specific Attributes On ActiveRecord Array](rails/check-specific-attributes-on-activerecord-array.md)
- [Code Statistics For An Application](rails/code-statistics-for-an-application.md)
- [Columns With Default Values Are Nil On Create](rails/columns-with-default-values-are-nil-on-create.md)

View File

@@ -0,0 +1,27 @@
# Check If Any Records Have A Null Value
I like to add missing `not null` constraints where appropriate when they are
missing. The [`change_column_null`
method](change-the-nullability-of-a-column.md) is the Rails DSL way of doing
this.
But first, you need to be sure that all databases this will be running against
don't have any `null` values already present for any records. If there are
`null` values present, then the migration will fail.
One way of doing that check is with some SQL and the
[`select_values`](https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-select_values)
method.
```ruby
ActiveRecord::Base
.connection
.select_values("select id from projects where user_id is null")
.any?
```
This bit of SQL asks for the `id`s of any records in the `projects` table where
a specific column (`user_id`) is explicitly `null`.
If this returns `false`, then you are good to migrate. If this returns `true`,
then you'll have to do some data massaging first.