首页 > 解决方案 > 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.

标签: ruby-on-railsruby-on-rails-5

解决方案


如果您使用 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

推荐阅读