Skip to content

Commit 61d3f6c

Browse files
committed
Support conditions option of UniquenessValidator
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.
1 parent c7e7de3 commit 61d3f6c

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#882](https://github.com/rubocop/rubocop-rails/pull/882): Fix false positive for `Rails/UniqueValidationWithoutIndex` with :conditions option. ([@etiennebarrie][])

lib/rubocop/cop/rails/unique_validation_without_index.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,20 +139,20 @@ def condition_part?(node)
139139
pairs = node.arguments.last
140140
return unless pairs.hash_type?
141141

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

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

147-
condition_hash_part?(uniqueness_node)
147+
condition_hash_part?(uniqueness_node, keys: %i[if unless conditions])
148148
end
149149

150-
def condition_hash_part?(pairs)
150+
def condition_hash_part?(pairs, keys:)
151151
pairs.each_pair.any? do |pair|
152152
key = pair.key
153153
next unless key.sym_type?
154154

155-
key.value == :if || key.value == :unless
155+
keys.include?(key.value)
156156
end
157157
end
158158

spec/rubocop/cop/rails/unique_validation_without_index_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,16 @@ class Article
371371
end
372372
RUBY
373373
end
374+
375+
it 'does not register an offense with a conditions option on the specific validator' do
376+
expect_no_offenses(<<~RUBY)
377+
class Article
378+
belongs_to :user
379+
enum :status, [:draft, :published]
380+
validates :user, uniqueness: { conditions: -> { published } }
381+
end
382+
RUBY
383+
end
374384
end
375385

376386
context 'without column definition' do

0 commit comments

Comments
 (0)