# Problems with associations and sorting

**URL:** <https://www.ruby-forum.com/t/problems-with-associations-and-sorting/127070>\
**Category:** Rails\
**Created:** [January 24, 2008, 6:11pm UTC](https://www.ruby-forum.com/t/problems-with-associations-and-sorting/127070 "2008-01-24T18:11:09Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jfoxny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/a6a055/32.png) [@jfoxny](https://www.ruby-forum.com/u/jfoxny)\
**Post date:** [January 24, 2008, 6:11pm UTC](https://www.ruby-forum.com/t/problems-with-associations-and-sorting/127070/1 "2008-01-24T18:11:09Z")

</div>

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  
end  
}

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”  
end

class TypeEvent \< ActiveRecord::Base  
belongs\_to :type  
belongs\_to :sales\_order  
end

class Type \< ActiveRecord::Base  
has\_many :type\_events  
end

create\_table “type\_events”, :force =\> true do |t|  
t.column “sales\_order\_id”, :integer  
t.column “type\_id”, :integer  
t.column “created\_at”, :datetime  
end

create\_table “types”, :force =\> true do |t|  
t.column “type\_name”, :string  
end

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.
