Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Default Sort Order For Rails models (See related posts)

// provide a default sort order in case an order by clause isn't defined in the find clause
// Place this code somewhere in your model's class file.

        def self.find(*args)
          order_arg = args.collect do |arg|
            if arg.kind_of? Hash 
              if arg.keys[0] == :order
                arg
              end
            end
          end

          if order_arg.compact.empty?
            args << {:order=>"place order by clause here e.g. 'name asc'"}
          end
          
          super
        end

Comments on this post

thefroze posts on Mar 22, 2008 at 17:06
How about?
def self.find(*args)
  args << {:order => 'due ASC'} if not :order in args 
  super
end
thefroze posts on Mar 22, 2008 at 17:09
Actually that wasnt valid

  def self.find(*args)
    if not args.include? :order
      args << {:order => 'column_name ASC'} 
    end
    super
  end
davidfrey posts on Mar 23, 2008 at 04:25
That doesn't quite seem right either.. you're going to end up with two hashes using
<<
according to the the rails api (http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001376) the options hash is the last parameter, so the second hash would override any other options passed in from the original find or through inheritance.

Sample args array from thefroze's solution
[:all, {:joins=>"INNER JOIN courses_people ON courses.id = courses_people.course_id", :limit=>nil, :readonly=>false, :select=>nil, :group=>nil, :offset=>nil, :include=>nil, :conditions=>"courses_people.person_id = 2 "}, {:order=>"position"}]


I came up with this variation--though it may be a bit more messy

def self.find(*args)
  options = args.last.is_a?(Hash) ? args.pop : {}
  if not options.include? :order
    options[:order] = 'position'
    args.push(options)
  end
  super
end


Sample args array from my solution
[:all, {:joins=>"INNER JOIN courses_people ON courses.id = courses_people.course_id", :limit=>nil, :readonly=>false, :select=>nil, :group=>nil, :offset=>nil, :order=>"position", :include=>nil, :conditions=>"courses_people.person_id = 2 "}]

You need to create an account or log in to post comments to this site.


Click here to browse all 4839 code snippets

Related Posts