Home > Announcements > What gets validated?

What gets validated?

Say you have a model called Match with attributes wins and losses, both of type integer.  To this model you add validation to ensure these attributes are only integers:

class Match < ActiveRecord::Base
 validates_numericality_of :wins, :only_integer => true
 validates_numericality_of :losses, :only_integer => true
end

Then, in script/console:

>> m = Match.new
=> #<Match id: nil, wins: nil, losses: nil, created_at: nil, updated_at: nil>
>> m.wins = "seven"
=> "seven"
>> m.losses = "five"
=> "five"
>> m
=> #<Match id: nil, wins: 0, losses: 0, created_at: nil, updated_at: nil>
>> m.valid?
=> false

The strings have been cast as integers, but why does the validation fail?  The answer is that ActiveRecord stores much more information than what shows up as instance attributes.

>> m.attributes_before_type_cast
=> {"created_at"=>nil, "losses"=>"five", "updated_at"=>nil, "wins"=>"seven"}

An indepth look at all of the machinery of ActiveRecord might be a course in itself, but I thought this would provide a taste of the breadth and depth of the ORM.

Categories: Announcements Tags:
  1. No comments yet.
  1. No trackbacks yet.