The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Sortable ActiveRecord Models

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Obie Fernandez

Posts: 608
Nickname: obie
Registered: Aug, 2005

Obie Fernandez is a Technologist for ThoughtWorks
Sortable ActiveRecord Models Posted: Mar 29, 2007 2:42 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Obie Fernandez.
Original Post: Sortable ActiveRecord Models
Feed Title: Obie On Rails (Has It Been 9 Years Already?)
Feed URL: http://jroller.com/obie/feed/entries/rss
Feed Description: Obie Fernandez talks about life as a technologist, mostly as ramblings about software development and consulting. Nowadays it's pretty much all about Ruby and Ruby on Rails.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Obie Fernandez
Latest Posts From Obie On Rails (Has It Been 9 Years Already?)

Advertisement

Most of the time you should let your database order your ActiveRecord models, but every once in awhile you need to order an array of them using Ruby's sort method. Here's a neat little hack which might be useful to you if have a bunch of models with name attributes:

class ActiveRecord::Base
  
  def <=>(other)
    if respond_to?(:name) and other.respond_to?(:name)
      name <=> other.name
    else
      super
    end
  end
  
end

You can keep extensions like this one in a directory named /lib/core_ext of your Rails application. Remember to require it in your environment.rb file, and that like any Ruby script that is explicitly required, it won't reload dynamically when changed. (server restart needed)

Read: Sortable ActiveRecord Models

Topic: Turn finders into associations and get caching for free Previous Topic   Next Topic Topic: Rails on 1.9: first benchmarks, YARV exposed to non-synthetic tests

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use