Skip to content

Commit

Permalink
Support conditions option of UniquenessValidator
Browse files Browse the repository at this point in the history
Since the `:conditions` option is a callable, we can't know exactly
which columns are necessary for the index, and the index is not required
to be unique anymore (maybe the conditions make the uniqueness only
apply to some records), it's not possible to add an offense when the
option is used.
  • Loading branch information
etiennebarrie committed Dec 7, 2022
1 parent c7e7de3 commit 61d3f6c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/fix_support_conditions_option_of.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#882](https://github.com/rubocop/rubocop-rails/pull/882): Fix false positive for `Rails/UniqueValidationWithoutIndex` with :conditions option. ([@etiennebarrie][])
8 changes: 4 additions & 4 deletions lib/rubocop/cop/rails/unique_validation_without_index.rb
Original file line number Diff line number Diff line change
Expand Up @@ -139,20 +139,20 @@ def condition_part?(node)
pairs = node.arguments.last
return unless pairs.hash_type?

return true if condition_hash_part?(pairs)
return true if condition_hash_part?(pairs, keys: %i[if unless])

uniqueness_node = uniqueness_part(node)
return unless uniqueness_node&.hash_type?

condition_hash_part?(uniqueness_node)
condition_hash_part?(uniqueness_node, keys: %i[if unless conditions])
end

def condition_hash_part?(pairs)
def condition_hash_part?(pairs, keys:)
pairs.each_pair.any? do |pair|
key = pair.key
next unless key.sym_type?

key.value == :if || key.value == :unless
keys.include?(key.value)
end
end

Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/rails/unique_validation_without_index_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,16 @@ class Article
end
RUBY
end

it 'does not register an offense with a conditions option on the specific validator' do
expect_no_offenses(<<~RUBY)
class Article
belongs_to :user
enum :status, [:draft, :published]
validates :user, uniqueness: { conditions: -> { published } }
end
RUBY
end
end

context 'without column definition' do
Expand Down

0 comments on commit 61d3f6c

Please sign in to comment.