gpt4 book ai didi

ruby-on-rails - 数值验证,在比较中捕获 nil 值

转载 作者:行者123 更新时间:2023-12-04 06:32:43 25 4
gpt4 key购买 nike

我有一个包含数字范围和描述 [min_val, max_val, name] 的对象。
我需要验证 min_val < max_val。但是,如果其中一个是空白的,我会得到一个 nil 比较错误,相反,我想告诉用户需要一个数字。

另外,如何更改数字的错误消息?

validates :min_val, :presence => true, :numericality => {:greater_than => 0, :less_than => :max_val}

validates :max_val, :presence => true, :numericality => {:greater_than => 0, :greater_than => :min_val}

validates :name, :presence => true, :if => Proc.new { |r| !r.min_val.nil? || !r.max_val.nil? }

最佳答案

您可以使用 :message指定自定义错误消息。

validates :max_val, :presence => true, :numericality => {:greater_than => 0, :message => " is an invalid number."}
validates :min_val, :presence => true, :numericality => {:greater_than => 0, :message => " is an invalid number."}
validate do |record|
record.errors.add_to_base("The min_val should be less than max_val") if min_val.to_i >= max_val.to_i
end
validates :name, :presence => true, :if => Proc.new { |r| !r.min_val.nil? || !r.max_val.nil? }

关于ruby-on-rails - 数值验证,在比较中捕获 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5208895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com