Reputation: 1199
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
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
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