Member.buddies.sort >> undefined method `<=>'

Hi all

I have a model Member that has a habtm relationship to buddies (also
members).
Now I wanted to sort them using sort, but this ends in an error
“undefined method <=>”! Where’s the problem here? Sorry, I’m still
beginning to learn Ruby. :wink:

Thanks
Josh

On Jan 11, 2006, at 4:01 PM, Joshua M. wrote:

Hi all

I have a model Member that has a habtm relationship to buddies (also
members).
Now I wanted to sort them using sort, but this ends in an error
“undefined method <=>”! Where’s the problem here? Sorry, I’m still
beginning to learn Ruby. :wink:

Thanks
Josh

It sounds like you’re trying to sort ActiveRecord objects, but the
trouble with that is there is no “right” way to sort them–by first
name? last name? date at which they were created? backwards?

You have two options: sort them at the database level, or with Ruby.

Database level:

class Member < ActiveRecord::Base
has_and_belongs_to_many :buddies, :class_name => ‘Member’ …
etc …, :sort => ‘lastname, firstname’
end

This will fetch your associated ‘buddies’ in alphabetical order
(lastname, ascending) for each Member object.

Alternatively, you can do it in Ruby code like this (probably what
you tried):

members = Member.find(:all)
sorted = members.sort { |m1, m2| m1.lastname <=> m2.lastname }

This will sort by lastname. There’s a shortcut method in Ruby 1.8
called ‘sort_by’ as well. Robby R. recently posted a great
article at the oreilly ruby blog (O'Reilly Media - Technology and Business Training).
Unfortunately I can’t find his article there, so look here for a copy
instead: Swik - Swik News
+Hashes+with+Ruby+and+Enumerable/bmqu

Duane J.
(canadaduane)
http://blog.inquirylabs.com/

Thanks a lot for your answer!

I have done it like that now:

has_and_belongs_to_many :buddies,
:class_name => ‘Member’,
:join_table => ‘members_have_buddies’,
:association_foreign_key => ‘buddy_id’,
:sort => ‘username’

but I receive an error now:

Unknown key(s): sort

What’s the problem? Thanks. :slight_smile:

Joshua M. wrote:

but I receive an error now:

Unknown key(s): sort

What’s the problem? Thanks. :slight_smile:

Try
:order => ‘username’

// JoNtE

Jonas Montonen wrote:

Try
:order => ‘username’

// JoNtE

Thanks, this works perfectly.