简体   繁体   中英

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, please help, 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'

error is like this

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

您能否尝试以下代码:

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' }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM