gpt4 book ai didi

ruby-on-rails - 控制 Rails 验证的顺序

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

我有一个 Rails 模型,其中有 7 个数字属性,由用户通过表单填写。

我需要验证每个属性是否存在,这显然很容易使用

validates :attribute1, :presence => true
validates :attribute2, :presence => true
# and so on through the attributes

但是,我还需要运行一个自定义验证器,它接受许多属性并用它们进行一些计算。如果这些计算的结果不在一定范围内,则该模型应被宣告无效。

就其本身而言,这也很容易

validate :calculations_ok?

def calculations_ok?
errors[:base] << "Not within required range" unless within_required_range?
end

def within_required_range?
# check the calculations and return true or false here
end

但是问题是方法“validate”总是在方法“validates”之前运行。这意味着,如果用户将必填字段之一留空,rails 在尝试使用空白属性进行计算时会抛出错误。

那么我怎样才能首先检查所有必需的属性是否存在?

最佳答案

我不确定是否能保证这些验证按什么顺序运行,因为它可能取决于 attributes 哈希本身的最终排序方式。您可能最好让您的 validate 方法更具弹性,并且在缺少某些所需数据时根本不运行。例如:

def within_required_range?
return if ([ a, b, c, d ].any?(&:blank?))

# ...
end

如果变量 ad 中的任何一个变量为空(包括 nil、空数组或字符串等),这将会退出。

关于ruby-on-rails - 控制 Rails 验证的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5966055/

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