dgmora
dgmora

Reputation: 1269

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.

Upvotes: 1

Views: 2149

Answers (1)

Billy Kimble
Billy Kimble

Reputation: 820

If you're using ActiveRecord to back your model, your dates and time fields are automatically parsed before being inserted.

# 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

So it comes down to validating the date format, which you can do manually with a regex, or you can call Date.parse and check for an exception:

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

Upvotes: 1

Related Questions