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

Rails/UniqueValidationWithoutIndex should not fail when a unique constraint is set #1393

Open
RubenSmit opened this issue Dec 13, 2024 · 0 comments

Comments

@RubenSmit
Copy link

In Rails 7.1 support was added for PostgreSQL unique constraints (rails/rails#46192). This makes it possible to defer checking for constraints inside transactions. This means uniqueness checking can be moved from the index to an unique constraint with add_unique_constraint and this is added to the schema.
Currently rubocop checks the schema for a uniqueness index on the field when a unique validation is set. But it should also accept a unique constraint.


Expected behavior

The unique validation without index cop should not fail when a unique constraint is set on the database column.

Actual behavior

Rails/UniqueValidationWithoutIndex: Uniqueness validation should have a unique index on the database column.

Steps to reproduce the problem

In Rails 7.1 or newer with a PostgreSQL database, create an index for a number field of a model with a deferrable uniqueness constraint.

class DeferModelFieldUniqueness < ActiveRecord::Migration
  def change
    # Note that we add an index without enforcing uniqueness
    add_index :model, :field, name: 'index_models_on_field'

    # Ensure the field is unique. Deferrable is set to true to enable changing the field in bulk inside a transaction
    add_unique_constraint :model,
                          :field,
                          deferrable: :deferred,
                          name: 'unique_model_field'
  end
end

Add a validation to the model:

  validates :field, uniqueness: true

RuboCop version

$ [bundle exec] rubocop -V
1.69.1 (using Parser 3.3.6.0, rubocop-ast 1.36.2, analyzing as Ruby 3.3, running on ruby 3.3.5) [x86_64-linux]
  - rubocop-capybara 2.21.0
  - rubocop-factory_bot 2.26.1
  - rubocop-performance 1.20.2
  - rubocop-rails 2.26.2
  - rubocop-rspec 2.31.0
  - rubocop-rspec_rails 2.29.1
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

No branches or pull requests

1 participant