Validates uniqueness with one exception

Asked

Viewed 18 times

0

Good morning,

I am a beginner in Rails and I have the following problem:

I need to do a validation on my model where the content needs to be unique except when it is '000000'.

I’ve tried to use:

validates :registration, uniqueness: true, exclusion: {in: '000000'}
validates :registration, uniqueness: true, unless: {in: '000000'}
end

Someone could help me make this validation work?

1 answer

0

A possible solution would be to create a validation method (which should return true or false) and call it in the unless clause of the validates:

    validates :registration, uniqueness: true, unless: :registration_equals_zero

   def registration_equals_zero
     registration == '000000'
   end

I ran the test here, using Rails 6.1

More information: https://guides.rubyonrails.org/active_record_validations.html#conditional-validation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.