Forum: Ruby on Rails how does rails handle wrong/malformed datatypes

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
087c7ed20dbea8082a89b8b8564bb9dd?d=identicon&s=25 Austin 7873 (austin7873)
on 2007-03-01 19:32

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?
8310c5a7c769345114597bcdef111488?d=identicon&s=25 Ben Munat (Guest)
on 2007-03-01 20:24
(Received via mailing list)
Heh. Found it last night: before_type_cast. So take a look at the value
of birthdate_before_type_cast in your controller. :-)

This topic is locked and can not be replied to.