Skip to content

Commit 507c88c

Browse files
authored
Merge pull request #1265 from ccutrer/not-null-column-docs
[Fix #237] Improve documentation for Rails/NotNullColumn
2 parents 1e4f28b + ddd3f50 commit 507c88c

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

config/default.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -693,7 +693,7 @@ Rails/NegateInclude:
693693
VersionChanged: '2.9'
694694

695695
Rails/NotNullColumn:
696-
Description: 'Do not add a NOT NULL column without a default value.'
696+
Description: 'Do not add a NOT NULL column without a default value to existing tables.'
697697
Enabled: true
698698
VersionAdded: '0.43'
699699
VersionChanged: '2.20'

lib/rubocop/cop/rails/not_null_column.rb

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,25 @@
33
module RuboCop
44
module Cop
55
module Rails
6-
# Checks for add_column call with NOT NULL constraint in migration file.
6+
# Checks for add_column calls with a NOT NULL constraint without a default
7+
# value.
78
#
8-
# `TEXT` can have default values in PostgreSQL, but not in MySQL.
9-
# It will automatically detect an adapter from `development` environment
10-
# in `config/database.yml` or the environment variable `DATABASE_URL`
11-
# when the `Database` option is not set. If the database is MySQL,
12-
# this cop ignores offenses for the `TEXT`.
9+
# This cop only applies when adding a column to an existing table, since
10+
# existing records will not have a value for the new column. New tables
11+
# can freely use NOT NULL columns without defaults, since there are no
12+
# records that could violate the constraint.
13+
#
14+
# If you need to add a NOT NULL column to an existing table, you must add
15+
# it as nullable first, back-fill the data, and then use
16+
# `change_column_null`. Alternatively, you could add the column with a
17+
# default first to have the database automatically backfill existing rows,
18+
# and then use `change_column_default` to remove the default.
19+
#
20+
# `TEXT` cannot have a default value in MySQL.
21+
# The cop will automatically detect an adapter from `development`
22+
# environment in `config/database.yml` or the environment variable
23+
# `DATABASE_URL` when the `Database` option is not set. If the database
24+
# is MySQL, this cop ignores offenses for `TEXT` columns.
1325
#
1426
# @example
1527
# # bad
@@ -26,7 +38,7 @@ module Rails
2638
# t.string :name, null: false, default: ''
2739
# end
2840
# add_reference :products, :category
29-
# add_reference :products, :category, null: false, default: 1
41+
# change_column_null :products, :category_id, false
3042
class NotNullColumn < Base
3143
include DatabaseTypeResolvable
3244

0 commit comments

Comments
 (0)