如何在 Ruby 中添加条件模型验证

How to add model validation with condition in Ruby

仅当所选国家/地区等于印度时,我才尝试对 gstno 进行模型验证。我试过这样不起作用:

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'

错误是这样的:

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

您可能希望将其移至自定义验证方法

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

self 将在那里供您使用

你能试试下面的代码吗:

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