Annoying rails date validation
I spent a good amount of time breaking my head over why a date field wasn’t getting set in one of the model after retrieving it’s value from a form. It turns out that if you pass a random string and not an actual date, rails will silently assign a nil to that field without complaining.
For example, I have a class Fact with date fields called from and to. Notice what is happening.
script/console
Loading development environment (Rails 2.3.3)
>> fact = Fact.new
=> #<Fact id: nil, from: nil, to: nil, timeToCount: nil, val: nil, remarks: nil, cp_detail_id: nil, created_at: nil, updated_at: nil>
>> fact.from = "foo"
=> "foo"
>> fact
=> #<Fact id: nil, from: nil, to: nil, timeToCount: nil, val: nil, remarks: nil, cp_detail_id: nil, created_at: nil, updated_at: nil>
>> fact.from = DateTime.now
=> Sun, 13 Sep 2009 09:53:29 -0600
>> fact
=> #<Fact id: nil, from: "2009-09-13 09:53:29", to: nil, timeToCount: nil, val: nil, remarks: nil, cp_detail_id: nil, created_at: nil, updated_at: nil>
When I assign a value foo, it doesn’t complain but just assigns a nil. Only if it had complained, I could have saved so much of my brain cells and time. Sigh …
Now, you might ask why am I assigning a foo instead of date. Well, I am still developing and was just putting random values to get the form to work :P
Anyway, I hope it will help some nOOb like me someday.
Have a good week,
Mahesh Murthy