class Listing < ActiveRecord::Base
belongs_to :book
belongs_to :guide
def <=>(other)
self.guide.name <=> other.guide.name
end
end
Book.find(1).listings.map{ |l| l.guide.name }
# => ["XYZZY", "BAR", "FOO", "QUUX"]
Book.find(1).listings.sort.map{ |l| l.guide.name }
# => ["BAR", "FOO", "QUUX", "XYZZY"]
Nice.







Ahhh…but what does the SQL look like?
SELECT * FROM `listings` WHERE (`listings`.book_id = 2)
As many selects from the `guides` table as there are listings.
SELECT * FROM `listings` WHERE (`listings`.book_id = 2)
SELECT * FROM `guides` WHERE (`guides`.`id` = 8)
SELECT * FROM `guides` WHERE (`guides`.`id` = 2)
SELECT * FROM `guides` WHERE (`guides`.`id` = 4)
SELECT * FROM `guides` WHERE (`guides`.`id` = 1)
SELECT * FROM `guides` WHERE (`guides`.`id` = 7)
SELECT * FROM `guides` WHERE (`guides`.`id` = 5)