【发布时间】:2026-02-22 11:45:02
【问题描述】:
我的 ActiveRecord 模型(在 Rails 中)中有一个日期时间字段,当日期字段超出范围时,我需要保护我的模型不崩溃。
我找到了this 的问题并尝试做出类似的做法:
class Something < ActiveRecord::Base
validate :important_date_is_valid_datetime, on: :create
validates :important_date, presence: true
private
def important_date_is_valid_datetime
if (DateTime.parse(important_date.to_s()) rescue ArgumentError) == ArgumentError then
errors.add(:important_date, 'must be a valid datetime')
end
end
end
此代码可以“验证”日期时间字段,但如果 valie 超出范围,它不会中止字段解析:
irb(main):007:0> Something.new(important_date: "2015-20-40").valid?
ArgumentError: argument out of range
from /home/shau-kote/.gem/ruby/2.1.0/gems/activesupport-4.2.0/lib/active_support/values/time_zone.rb:350:in `initialize'
from /home/shau-kote/.gem/ruby/2.1.0/gems/activesupport-4.2.0/lib/active_support/values/time_zone.rb:350:in `new'
from /home/shau-kote/.gem/ruby/2.1.0/gems/activesupport-4.2.0/lib/active_support/values/time_zone.rb:350:in `parse'
...
我可以防止类似的崩溃吗?
【问题讨论】:
标签: ruby-on-rails datetime activerecord