views:

63

answers:

1

I came across this idiosyncrasy while testing my validations. With a migration defined as follows:

create_table :time_windows do |t|
  t.datetime :window_begin, :null => true
  t.datetime :window_end, :null => true
end

in irb

>> t = TimeWindow.new({:window_begin  => Time.now, :window_end => "not a time"})
=> #<TimeWindow id: nil, window_begin: "2010-07-29 15:54:07", window_end: nil>

My question is, why ActiveRecord interprets "not a time" as nil rather than just setting :window_end = "not a time"? The same translation-to-nil happens when you set :window_end to an int as well.

The reason this is a problem for me is if someone tries to save a non Time value in the :window_end (or :window_start) column, I'd like an error to be thrown, but that will not be the case here.

Thanks.

A: 

First of all database cannot save a string in a datetime column. Second, Rails interpret "not a time" as nil because you don't have time value, i.e. you have nil.

Finally, it's your responsibility to validate your input. You can do it something like this: http://stackoverflow.com/questions/1370926/rails-built-in-datetime-validation/1371350#1371350

Slobodan Kovacevic
I think my question was poorly phrased. Forget saving it to the database for a second. When I create the TimeWindow object in memory with an illegal (not Time) value for the :window_end attribute, it just instantiates the object with nil for :window_end. However, if I instantiate an different model class with an attribute :count of type integer, for instance, and assign :count => "not a number", the object is instantiated with :count = "not a number". Why the translation of String -> nil in the former case but not in the latter?
Big Bird
That's not true for integer attributes. I just did following in one of my projects: u = User.new(:sign_in_count => "not a number") [btw, sign_in_count is integer attr] and when I called u.sign_in_count I got: 0. The reason for this is because "not a number" is casted using to_i which returns 0 ("not a number".to_i => 0)
Slobodan Kovacevic