Problems with associations and sorting

I have the following code that always fails with “comparison of String
with 0 failed”. Here’s the sort I’m trying to do:

orders = SalesOrder.find(:all, :include => [:latest_type]).sort{ |a,b|
if a.latest_type.nil? and b.latest_type.nil?; 0
elsif a.latest_type.nil?; 1
elsif b.latest_type.nil?; -1
else; b.latest_type.type_id <=> a.latest_type.type_id

This never works, and I can’t figure out why. I think it has something
to do with my associations (and their schemas):

class SalesOrder < ActiveRecord::Base
has_one :latest_type,
:class_name => “TypeEvent”,
:order => “created_at desc”

class TypeEvent < ActiveRecord::Base
belongs_to :type
belongs_to :sales_order

class Type < ActiveRecord::Base
has_many :type_events

create_table “type_events”, :force => true do |t|
t.column “sales_order_id”, :integer
t.column “type_id”, :integer
t.column “created_at”, :datetime

create_table “types”, :force => true do |t|
t.column “type_name”, :string

Can anyone help me, or at least point me in a direction here? I would
really like to compare by latest_type.type.type_name, but I can’t figure
out how to do it.