SkRoR
SkRoR

Reputation: 1199

How to add model validation with condition in Ruby

I am trying to do model validation for gstno only if the selected country equals India. I tried like this not working:

validates :gstno, uniqueness: true, :format => {:with => /[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}/, :message => 'INCORRECT FORMAT!'} if self.country =='IN'

The error is like this:

undefined method `country' for #<Class:0x007fb021d6a0c8> Did you mean? count

Upvotes: 0

Views: 42

Answers (2)

MrShemek
MrShemek

Reputation: 2483

Can you please try the following code:

validates :gstno, uniqueness: true, :format => {:with => /[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}/, :message => 'INCORRECT FORMAT!'}, if: -> { country == 'IN' }

Upvotes: 2

vinyl
vinyl

Reputation: 569

You probably want to move this to a custom validation method

https://guides.rubyonrails.org/active_record_validations.html#custom-methods

self will be available to you there

Upvotes: 1

Related Questions