views:

23

answers:

1

If you assign an invalid date (like December 39th) to a datetime column ActiveRecord returns a "can't be blank" error when is should probably return an error like "Not a valid date"

My question. Is this expected rails behavior, a bug or, something that I could patch?

class ExerciseLog < ActiveRecord::Base
  validates_presence_of :scheduled_datetime
end

Fire up the console.

e = Log.new
# lets set a date for Dec 39th which obviously doesn't exist
e.scheduled_datetime = "2010-12-39"
e.save
=> false
# this is the confusing message since our form did post a valid date
e.errors.on(:scheduled_datetime)
=> "can't be blank"
e.scheduled_datetime = "2010-12-30"
e.save
=> true

I discovered this issue when I accidentally transposed the month and day values.

btw This is in Rails 2.3.5

+1  A: 

My guess, without digging through the rails code, is that that magic parsing that rails does with the date returns nil when an invalid string is assigned to a Date column.

If you do t = Date.parse("2010-12-39") in the rails console then you get:

ArgumentError: invalid date
    from /usr/local/lib/ruby/1.8/date.rb:931:in `new_by_frags'
    from /usr/local/lib/ruby/1.8/date.rb:975:in `parse'
    from (irb):2
    from :0

I am guessing that rails traps this error and sets the value to nil. Thus firing off the validation.

Tony Fontenot