Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix false positive in UniquenessValidator with conditions #882

Merged
merged 2 commits into from
Dec 8, 2022

Conversation

etiennebarrie
Copy link
Contributor

@etiennebarrie etiennebarrie commented Dec 7, 2022

First, a validation can be defined with options specific to the validator:

class Article < ApplicationRecord
  validates :user, uniqueness: { if: -> { false } }
  # equivalent to
  # validates :user, uniqueness: true, if: -> { false }
end

And this should not add an offense, like when the :if is on the validates, because we don't know what the condition is and it could lead to a false positive.

Secondly, there's a :conditions option that can't be added on validates directly because it's specific to the UniquenessValidator, which can also lead to false positives, because it can refer to columns or otherwise reduce the uniqueness in a way that prevents a unique index from covering it in the schema.


  • The PR relates to only one subject with a clear title and description in grammatically correct, complete sentences.
  • Wrote good commit messages.
  • Commit message starts with [Fix #issue-number] (if the related issue exists).
  • Feature branch is up-to-date with master (if not - rebase it).
  • Squashed related commits together.
  • Added tests.
  • Ran bundle exec rake default. It executes all tests and runs RuboCop on its own code.
  • Added an entry (file) to the changelog folder named {change_type}_{change_description}.md if the new code introduces user-observable changes. See changelog entry format for details.
  • If this is a new cop, consider making a corresponding update to the Rails Style Guide.

validates can take a hash of options specific to one validator
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.
@koic koic merged commit c23478a into rubocop:master Dec 8, 2022
@koic
Copy link
Member

koic commented Dec 8, 2022

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants