44

I have

class Authors 
has_many :books, :order => 'name ASC'

I am trying to query all the books sorted by name DESC

Authors.books.order('name DESC')

but the result is

SELECT * FROM .... ORDER BY name ASC, name DESC

and the results come back with the name sorted ASC

is there a way to remove the original order in the association or override it? Or is specifying an order in a relation a bad idea?

using Rails 3.0.3

Christopher
  • 453
  • 1
  • 4
  • 5

3 Answers3

106

Use reorder:

Authors.books.reorder('name DESC')
mb21
  • 34,845
  • 8
  • 116
  • 142
Ariejan
  • 10,910
  • 6
  • 43
  • 40
  • That's great! Couldn't find it documented anywhere though; where did you find it? – Christopher Nov 17 '10 at 08:17
  • 2
    Actually, is this still valid? https://github.com/rails/rails/commit/e0b76d6151821527f16b3f163abde3ebea1b2a50 – Christopher Nov 17 '10 at 08:24
  • 3
    @Christopher ~ Not by my reading. May I suggest (which you probably already deduced from that post) accepting @Jon's answer below? – jcolebrand Dec 27 '10 at 05:44
  • Works also in Rails 5: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-reorder – mb21 Apr 16 '18 at 13:45
35

.reorder() has been deprecated in Rails 3.0.3 in favor of .except(:order).order()

So use this:

Authors.books.except(:order).order('name DESC')
mahemoff
  • 44,526
  • 36
  • 160
  • 222
Jon
  • 399
  • 3
  • 2
  • 3
    I don't see any deprecation warnings on rails 3.1.0.rc4 about #reorder, and `.except(:order).order()` doesn't exclude order clauses that are pulled in from associations. – ben_h Jul 05 '11 at 07:31
  • 1
    `.except(:order).order()` **does** exclude order clauses defined on associations. – Anjan Sep 25 '12 at 19:42
  • 3
    I don't see any mention of `reorder` being deprecated in Rails 3.2.8: http://apidock.com/rails/v3.2.8/ActiveRecord/QueryMethods/reorder – mxk Oct 18 '12 at 14:35
  • 4
    `reorder` is still valid in Rails 4.0.2: http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/reorder – cgenco Sep 16 '14 at 00:02
-1
Author.first.books.reverse_order
Subba Rao
  • 10,576
  • 7
  • 29
  • 31