diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d2adec450..c54c22db92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Bug fixes +* [#315](https://github.com/rubocop-hq/rubocop-rails/pull/315): Allow to use frozen scope for `Rails/UniqueValidationWithoutIndex`. ([@krim][]) * [#313](https://github.com/rubocop-hq/rubocop-rails/pull/313): Fix `Rails/ActiveRecordCallbacksOrder` to preserve the original callback execution order. ([@eugeneius][]) ### Changes @@ -256,3 +257,4 @@ [@jcoyne]: https://github.com/jcoyne [@fatkodima]: https://github.com/fatkodima [@taylorthurlow]: https://github.com/taylorthurlow +[@krim]: https://github.com/krim diff --git a/lib/rubocop/cop/rails/unique_validation_without_index.rb b/lib/rubocop/cop/rails/unique_validation_without_index.rb index 3251a22471..35c362b978 100644 --- a/lib/rubocop/cop/rails/unique_validation_without_index.rb +++ b/lib/rubocop/cop/rails/unique_validation_without_index.rb @@ -97,6 +97,8 @@ def column_names_from_scope(node) scope = find_scope(uniq) return unless scope + scope = unfreeze_scope(scope) + case scope.type when :sym, :str [scope.value] @@ -114,6 +116,10 @@ def find_scope(pairs) end end + def unfreeze_scope(scope) + scope.send_type? && scope.method?(:freeze) ? scope.children.first : scope + end + def class_node(node) node.each_ancestor.find(&:class_type?) end diff --git a/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb b/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb index 26cf30e83f..0cb7200fdd 100644 --- a/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb +++ b/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb @@ -179,6 +179,16 @@ class WrittenArticles end RUBY end + + context 'when scope is frozen' do + it 'does not register an offense' do + expect_no_offenses(<<~RUBY) + class WrittenArticles + validates :a_id, uniqueness: { scope: [:b_id, :c_id].freeze } + end + RUBY + end + end end end