Joshua Muheim
2006-Jan-11 23:01 UTC
[Rails] 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. ;-) Thanks Josh -- Posted via http://www.ruby-forum.com/.
Duane Johnson
2006-Jan-11 23:16 UTC
[Rails] Member.buddies.sort >> undefined method `<=>''
On Jan 11, 2006, at 4:01 PM, Joshua Muheim 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. ;-) > > Thanks > JoshIt 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 Russell recently posted a great article at the oreilly ruby blog (http://www.oreillynet.com/ruby). Unfortunately I can''t find his article there, so look here for a copy instead: http://swik.net/Ruby/O''Reilly+Ruby+Blog/Sorting+an+Array+of +Hashes+with+Ruby+and+Enumerable/bmqu Duane Johnson (canadaduane) http://blog.inquirylabs.com/
Joshua Muheim
2006-Jan-11 23:23 UTC
[Rails] Re: Member.buddies.sort >> undefined method `<=>''
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. :-) -- Posted via http://www.ruby-forum.com/.
Jonas Montonen
2006-Jan-12 09:09 UTC
[Rails] Re: Member.buddies.sort >> undefined method `<=>''
Joshua Muheim wrote:> 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. :-) > >Try :order => ''username'' // JoNtE