Validates_presence_of Date with '00' year fails

Hi there

I’ve come across an interesting scenario with validates_presence_of
and Dates in Rails. I’ve been looking through the Rails code but I
just can’t figure out where in Rails the date parsing which presumably
causes this issue is happening.

The problem is this. If you try and create a model using a date
string in the format “dd MMM yy” but you specify a year of ‘00’,
‘validates_presence_of’ fails because the Date object Rails converts
the String to is nil. If you specify any other 2-digit year it’s
fine. Here’s a simple example test case:

class Model
validates_presence_of :dated_on
end

this works

m = Model.create(:dated_on => ‘20 Apr 01’)
assert m.errors.empty?

this fails

m = Model.create(:dated_on => ‘20 Apr 00’)
assert m.errors.empty?

Has anyone come across this before and/or would anyone be able to
point me to where in the Rails code base the date is parsed so I can
look at implementing a workaround? I just can’t spot it!

Many thanks
Olly

Ultimately, the parsing of a date comes down to the new_date method in
activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb.
It’s currently on line 166 of that file in edge Rails. That method
returns
nil if the year is 0. I don’t know why it works that way, but at least
you
now know why you see the behavior that you do.

Regards,
Craig

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs