How does rails handle wrong/malformed datatypes


I need help understanding how rails handles setting object attributes
with the wrong datatype. Specifically a datetime attribute, but the
behavior happens with other data types too (I’ve also tried with

I’m thinking that rails does some magic behind the scenes and if it
senses that you’re trying
to set an attribute with the wrong data type, for example, datetime with
“asdf”, it returns nil, or integer with “asdf”, it returns 0.

Validating then becomes a bit more difficult!

In a real example, I have a people table in my database with a birthdate

create_table “people”, :force => true do |t|
t.column “name”, :string
t.column “age”, :integer
t.column “birthdate”, :datetime

On my form I try to submit a date with the value “abcdef”, which is not
a valid date format.
My people_controller.rb then creates a new instance of person and, for
now, simply prints the brithdate.

def create
@person =[:person])
puts @person.birthdate

or with “ruby script/console”

person =>“foo”, :age => “bar”, :birthdate => “baz”)
=> #<Person:0x327d80c @attributes={“name”=>“foo”, “age”=>“bar”
“birthdate”=>“baz”}, @new_record=true>

puts person.birthdate
=> nil

In either script/console, or the controller, if I print the whole object

puts person.to_xml

birthdate is also nil. however if I print with:

puts person.to_yaml

I do see the malformed value in the object. So from there, if I try to
do any validation in the person model, person.rb, during a save.

or in the controller

def create
@person =[:person])

I’m still not able to see the value in person.birthdate:

def validate
puts self.birthdate # returns nil
puts attributes[‘birthdate’] # returns nil
puts self.to_xml # returns a nil value for birthdate in the
puts self.to_yaml # returns the error “wrong argument type nil
(expected Data)”

How can I validate the date is in the correct format if the object
returns nil for the value?

Heh. Found it last night: before_type_cast. So take a look at the value
of birthdate_before_type_cast in your controller. :slight_smile: