How does rails handle wrong/malformed datatypes

Hi,

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
integers)

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
attribute:

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

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.new(params[:person])
puts @person.birthdate
end

or with “ruby script/console”

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

puts person.birthdate
nil
=> nil

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

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.

person.save

or in the controller

def create
@person = Person.new(params[:person])
@person.save
end

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
output
puts self.to_yaml # returns the error “wrong argument type nil
(expected Data)”
end

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:

b

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