Search code examples
validationruby-on-rails-4controllerdate-formatstrptime

How do I prevent strptime from throwing an error if my date isn't present or in the right format?


I’m using Rails 4.2.3. In my controller, I have this when I’m about to save an entity

    @date = Date.strptime(my_object_params[:day], "%m/%d/%Y")
    @my_object.day = @date
        respond_to do |format|
      if @my_object.save

Unfortunately, if the parameter is not included or if it doesn’t match the format, I get this error

ArgumentError (invalid date):
  app/controllers/my_objects_controller.rb:33:in `strptime'
  app/controllers/my_objects_controller.rb:33:in `create'

How can I prevent Rails from dying if it doesn’t get the right format? I have included this validation rule in my model, although I don’t think its getting to that stage yet, since my “Save” is not called until later in the method …

  validates_presence_of :day

Solution

  • Try being more specific in your error handling?

    begin
      @date = Date.strptime(my_object_params[:day], "%m/%d/%Y")
    rescue ArgumentError => ae
      #do something rational and valid
    end