Skip to content

Commit

Permalink
Merge pull request #1140 from koic/fix_false_positives_for_redundant_…
Browse files Browse the repository at this point in the history
…presence_validation_on_belongs_to

[Fix #1105] Fix false positives for `Rails/RedundantPresenceValidationOnBelongsTo`
  • Loading branch information
koic committed Oct 7, 2023
2 parents ebfb3ef + 1cca3cc commit bd7ee99
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1105](https://github.com/rubocop/rubocop-rails/issues/1105): Fix false positives for `Rails/RedundantPresenceValidationOnBelongsTo` when using `validates` with `:if` or `:unless` options. ([@koic][])
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ class RedundantPresenceValidationOnBelongsTo < Base
# @example source that matches - by a foreign key
# validates :user_id, presence: true
#
# @example source that DOES NOT match - if condition
# validates :user_id, presence: true, if: condition
#
# @example source that DOES NOT match - unless condition
# validates :user_id, presence: true, unless: condition
#
# @example source that DOES NOT match - strict validation
# validates :user_id, presence: true, strict: true
#
Expand All @@ -65,6 +71,7 @@ class RedundantPresenceValidationOnBelongsTo < Base
$[
(hash <$(pair (sym :presence) true) ...>) # presence: true
!(hash <$(pair (sym :strict) {true const}) ...>) # strict: true
!(hash <$(pair (sym {:if :unless}) _) ...>) # if: some_condition or unless: some_condition
]
)
PATTERN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,20 @@ class Profile
RUBY
end

it 'does not register an offense with `if` option' do
expect_no_offenses(<<~RUBY)
belongs_to :user
validates :user, presence: true, if: -> { condition }
RUBY
end

it 'does not register an offense with `unless` option' do
expect_no_offenses(<<~RUBY)
belongs_to :user
validates :user, presence: true, unless: -> { condition }
RUBY
end

it 'does not register an offense with strict validation' do
expect_no_offenses(<<~RUBY)
belongs_to :user
Expand Down

0 comments on commit bd7ee99

Please sign in to comment.