shoulda-matchers icon indicating copy to clipboard operation
shoulda-matchers copied to clipboard

`validate_uniqueness_of` doesn't work with STI in some cases

Open Exterm1nate opened this issue 3 years ago • 2 comments

Consider we have a parent model with uniqueness validation with scope:

class ParentModel < ActiveRecord::Base
  validates :column_1, uniqueness: { scope: :column_2 }
end

class ChildModel1 < ParentModel
end

class ChildModel2 < ParentModel
end

If we try to validate the uniqueness of column column_1 scoped to column_2 an example always fails, because in Rails (v7) child model doesn't return parent model's validations info on validators_on call.

ChildModel1.validators_on(:column_1) 
#=> []

ParentModel.validators_on(:column_1) 
#=> [#<ActiveRecord::Validations::UniquenessValidator, @attributes=[:column_1], @klass=ChildModel1, @options={:scope=>:column_2}>]

Maybe this should be changed in Rails itself, but for now it is better to fix this bug here.

Exterm1nate avatar Aug 08 '22 23:08 Exterm1nate

Hello! Thanks for reporting this issue. @bigchickenwings and I planned to work on this issue, but we couldn't reproduce the behaviour you mentioned.

We used rails 7.0.3.1 with the following script:

rails new sti_example
cd sti_example
rails g model Vehicle color:string model:string type:string
rails g model Car --skip-migration
rails g model Motorcycle --skip-migration
rails db:create db:migrate
class Vehicle < ApplicationRecord
  validates :color, uniqueness: { scope: :model }
end

class Car < Vehicle
end

Car.validators_on(:color)
#=> [#<ActiveRecord::Validations::UniquenessValidator:0x000000014116c168 @attributes=[:color], @klass=Vehicle (call 'Vehicle.connection' to establish a connection), @options={:scope=>:model}>]

Vehicle.validators_on(:color)
#=> [#<ActiveRecord::Validations::UniquenessValidator:0x000000014116c168 @attributes=[:color], @klass=Vehicle (call 'Vehicle.connection' to establish a connection), @options={:scope=>:model}>]

Are we doing something different than the example that you provided?

matsales28 avatar Sep 02 '22 18:09 matsales28

Seems like problem is on Rails side.

Delegated to Rails project (https://github.com/rails/rails/issues/45939), so think we can close this issue.

Exterm1nate avatar Sep 03 '22 14:09 Exterm1nate