【问题标题】:How to add model validation with condition in Ruby如何在 Ruby 中添加带有条件的模型验证
【发布时间】:2019-03-12 18:30:05
【问题描述】:

仅当所选国家/地区等于印度时,我才尝试对 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

【问题讨论】:

    标签: ruby-on-rails activemodel


    【解决方案1】:

    你能试试下面的代码吗:

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

    【讨论】:

      【解决方案2】:

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

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

      self 将在那里为您提供服务

      【讨论】:

        猜你喜欢
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2013-05-24
        • 1970-01-01
        • 2020-05-19
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多