0
在我的Rails 4.1.6項目,我有一個數據庫表時間戳:自定義的驗證時間獲取對象,但需要字符串
create_table "jobs", force: true do |t|
...
t.timestamp "run_time", limit: 6
...
end
該模型包括該字段的自定義驗證:
class Job < ActiveRecord::Base
...
validates :run_time, iso_time: true
...
end
自定義驗證是:
require "time"
class IsoTimeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
p [value.class, value] #DEBUG
errors = []
unless Iso_8601.valid?(value)
errors << "is not an ISO-8601 time"
else
if options[:time_zone]
if Iso_8601.has_time_zone?(value) != options[:time_zone]
errors << [
"should",
("not" unless options[:time_zone]),
"have time zone"
].compact.join(' ')
end
end
end
set_errors(record, attribute, errors)
end
private
def set_errors(record, attribute, errors)
unless errors.empty?
if options[:message]
record.errors[attribute] = options[:message]
else
record.errors[attribute] += errors
end
end
end
end
這個驗證不起作用,因爲Rails不通過它的 屬性的原始字符串值。相反,在調用驗證器之前,Rails將 字符串轉換爲時間對象。如果字符串 不能轉換,它通過無給校驗:
Job.new(run_time: "ABC").save
# [nilClass, nil]
如果字符串可被轉換,它通過一個時間對象到 驗證:
Job.new(run_time: "01/01/2014").save
# [ActiveSupport::TimeWithZone, Wed, 01 Jan 2014 00:00:00 UTC +00:00]
驗證經過timestamp屬性,自定義驗證器 如何獲得對屬性的原始字符串值的訪問權限?