TL; DR:我在Rails 5.1中有一个ActiveRecord模型,它有一个复合字段,序列化为YAML到MySQL中的文本字段。我想要以非常具体的方式格式化日期字段,但Rails在写入数据库时试图变得聪明,我不明白为什么。
详情
我正试图坚持一个非常简单的模型
class ReportService < ApplicationRecord
# AR associations omitted
serialize :report_params, ReportParamsSerializer
end
报告params serialiser没有任何想象力,只是从字符串中删除一些引号(this SO question中解释的基本理由):
class ReportParamsSerializer
def self.dump(report_params)
yaml_string = report_params.to_yaml
quoted_date_regex = /\'(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)\'/
yaml_string.gsub!(quoted_date_regex, '\1 ')
yaml_string
end
def self.load(report_params)
YAML.load(report_params) unless report_params.nil?
end
end
这里report_params
只是一些哈希:
{"title"=>nil, "date_from"=>"2018-05-02 04:00:00", "date_to"=>"2018-05-03 03:59:00", "output"=>"PDF", ...}
将输出打印到控制台会给出我想要的YAML:
---
title:
date_from: 2018-05-02 04:00:00
date_to: 2018-05-03 03:59:00
...
但是,当我查看数据库时,我看到了:
---
title:
date_from: 2018-05-02 05:00:00.000000000 +01:00
date_to: 2018-05-03 04:59:00.000000000 +01:00
....
知道为什么会这样吗?
编辑:我添加了更多日志记录语句,以便在调用序列化程序时向我显示。
def self.dump(report_params)
yaml_string = report_params.to_yaml
puts "presubstitution: #{yaml_string}"
quoted_date_regex = /\'(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)\'/
yaml_string.gsub!(quoted_date_regex, '\1 ')
puts "post_substitution: #{yaml_string}"
yaml_string
end
正在运行
puts "report args: #{report_args.inspect}"
puts "as YAML:"
puts ReportParamsSerializer.dump(report_args[:report_params])
ReportService.create(report_args)
给我输出如:
as YAML:
presubstitution: ---
title:
date_from: '2018-05-01 23:00:00'
date_to: '2018-05-02 22:59:00'
...
post_substitution: ---
title:
date_from: 2018-05-01 23:00:00
date_to: 2018-05-02 22:59:00
---
title:
date_from: 2018-05-01 23:00:00
date_to: 2018-05-02 22:59:00
...
presubstitution: ---
title:
date_from: 2018-05-02 00:00:00.000000000 +01:00
date_to: 2018-05-02 23:59:00.000000000 +01:00
...
post_substitution: ---
title:
date_from: 2018-05-02 00:00:00.000000000 +01:00
date_to: 2018-05-02 23:59:00.000000000 +01:00
...
SQL (47.7ms) INSERT INTO `report_services` (other_stuff, `report_params`, ) VALUES (other_values, '---\ntitle: \ndate_from: 2018-05-02 00:00:00.000000000 +01:00\ndate_to: 2018-05-02 23:59:00.000000000 +01:00\ ...)
presubstitution: ---
title:
date_from: 2018-05-02 00:00:00.000000000 +01:00
date_to: 2018-05-02 23:59:00.000000000 +01:00
...
post_substitution: ---
title:
date_from: 2018-05-02 00:00:00.000000000 +01:00
date_to: 2018-05-02 23:59:00.000000000 +01:00