gpt4 book ai didi

ruby - 在 Rails 模型中更改自定义验证的优先级

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:04 25 4
gpt4 key购买 nike

我已经以依赖的方式实现了验证,比如如果 start_date 格式无效,那么我不想在 start_date 上运行其他验证。

 validates_format_of :available_start_date, :with =>  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}((((\-|\+){1}\d{2}:\d{2}){1})|(z{1}|Z{1}))$/, :message => "must be in the following format: 2011-08-25T00:00:00-04:00"

这会检查特定格式,然后我会调用自定义验证方法,稍后应该从中运行。

def validate
super
check_offer_dates
end

我已经使用 self.errors["start_date"] 检查错误对象是否包含错误,如果它不为空,它应该跳过对同一参数的其他验证。

但问题是首先调用 def validate,然后调用 validates_format_of。我该如何更改它才能实现流程。

最佳答案

我刚刚遇到了类似的问题;这就是我使用 before_save 标注修复它的方法:

不工作(验证顺序错误 - 我想最后进行自定义验证):

class Entry < ActiveRecord::Base
validates_uniqueness_of :event_id, :within => :student_id
validate :validate_max_entries_for_discipline

def validate_max_entries_for_discipline
# set validation_failed based on my criteria - you'd have your regex test here
if validation_failed
errors.add(:maximum_entries, "Too many entries here")
end
end
end

工作(使用 before_save 标注):

class Entry < ActiveRecord::Base
before_save :validate_max_entries_for_discipline!
validates_uniqueness_of :event_id, :within => :student_id

def validate_max_entries_for_discipline!
# set validation_failed based on my criteria - you'd have your regex test here
if validation_failed
errors.add(:maximum_entries, "Too many entries here")
return false
end
end
end

注意变化:

  1. validate_max_entries_for_discipline 变成 validate_max_entries_for_discipline!
  2. 验证方法现在在失败时返回 false
  3. validate validate_max_entries_for_discipline 变为 before_save validate_max_entries_for_discipline!

关于ruby - 在 Rails 模型中更改自定义验证的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8984350/

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