ruby-on-rails - Automatically parsing date/time parameters in rails
问题描述
Is there a way to automatically parse string parameters representing dates in Rails? Or, some convention or clever way?
Doing the parsing manually by just doing DateTime.parse(..)
in controllers, even if it's in a callback doesn't look very elegant.
There's also another case I'm unsure how to handle: If a date field in a model is nullable, I would like to return an error if the string I receive is not correct (say: the user submits 201/801/01
). This also has to be done in the controller and I don't find a clever way to verify that on the model as a validation.
解决方案
如果您使用 ActiveRecord 来支持您的模型,您的日期和时间字段会在插入之前自动解析。
# migration
class CreateMydates < ActiveRecord::Migration[5.2]
def change
create_table :mydates do |t|
t.date :birthday
t.timestamps
end
end
end
# irb
irb(main):003:0> m = Mydate.new(birthday: '2018-01-09')
=> #<Mydate id: nil, birthday: "2018-01-09", created_at: nil, updated_at: nil>
irb(main):004:0> m.save
=> true
irb(main):005:0> m.reload
irb(main):006:0> m.birthday
=> Tue, 09 Jan 2018
所以它归结为验证日期格式,您可以使用正则表达式手动执行此操作,或者您可以调用 Date.parse 并检查异常:
class Mydate < ApplicationRecord
validate :check_date_format
def check_date_format
begin
Date.parse(birthday)
rescue => e
errors.add(:birthday, "Bad Date Format")
end
end
end
推荐阅读
- oracle - 使同一表中 2 列中的值相互唯一
- php - 如何在php中正确转义数组?
- azure - 如何查看日志分析工作区中表的行数?
- reactjs - 无法解析“../../theme.config”
- combobox - 如何在后面的代码中访问 ComboBox 选定项
- javascript - Ajax 下载 gzip 文件 - 响应数据始终为字符串
- weblogic - cfgfwk-64254 在创建新域时执行安全处理阶段出错
- java - 如何创建ExpensiveGraph
- react-native - 在反应原生视频中添加字幕
- java - 如何在 Obsever Pattern 中处理多个 Observable 属性?