I have a little example Rails app called tickets, which views and edits fictional tickets sold to various customers. In tickets_controller.rb, inside def index
, I have this standard line, generated by scaffolding:
@tickets = Ticket.find(:all)
To sort the tickets by name, I have found two possible approaches. You can do it this way:
@tickets = Ticket.find(:all, :order => 'name')
... or this way:
@tickets = Ticket.find(:all).sort!{|t1,t2|t1.name <=> t2.name}
(Tip: Ruby documentation explains that sort!
will modify the array that it is sorting, as opposed to sort
alone, which returns the sorted array but leaves the original unchanged).
What strategy do you normally use? When might you use .sort!
versus the :order => 'criteria'
syntax?
Clarification
Originally, this question was going to be "why isn't the second approach working," but now it is working. Since I had documented two ways to do this, I thought I'd at least publish it for others to find. :)