【问题标题】:Validates_overlap custom message?Validates_overlap 自定义消息?
【发布时间】:2017-03-07 12:58:45
【问题描述】:

我尝试使用 gem validates_operator。 我需要为此验证自定义消息:

验证 :arrival_date、:departure_date、重叠:{
范围:“place_id”,
message_title: "错误",
message_content:"这个日期无法预订这个地方" }

但我有简单形式的默认消息:“请查看以下问题”

感谢未来的答案。

【问题讨论】:

    标签: ruby-on-rails ruby validates-associated


    【解决方案1】:

    您还可以创建验证模型状态的方法,并在它们无效时将消息添加到错误集合中。然后,您必须使用 validate (API) 类方法注册这些方法,并传入验证方法名称的符号。

    您可以为每个类方法传递多个符号,并且相应的验证将按照注册时的相同顺序运行。

    有效吗?方法将验证错误集合是否为空,因此当您希望验证失败时,您的自定义验证方法应向其中添加错误:

    class Invoice < ApplicationRecord
      validate :expiration_date_cannot_be_in_the_past,
        :discount_cannot_be_greater_than_total_value
    
      def expiration_date_cannot_be_in_the_past
        if expiration_date.present? && expiration_date < Date.today
          errors.add(:expiration_date, "can't be in the past")
        end
      end
    
      def discount_cannot_be_greater_than_total_value
        if discount > total_value
          errors.add(:discount, "can't be greater than total value")
        end
      end
    end
    

    默认情况下,每次调用 valid 时都会运行此类验证?或保存对象。但也可以通过为 validate 方法提供 :on 选项来控制何时运行这些自定义验证,使用::create 或 :update。

    class Invoice < ApplicationRecord
      validate :active_customer, on: :create
    
      def active_customer
        errors.add(:customer_id, "is not active") unless customer.active?
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-12
      • 2011-06-26
      • 2019-11-19
      • 1970-01-01
      • 2012-12-12
      相关资源
      最近更新 更多