Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override :order defined in a has_many

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

like image 292
Christopher Avatar asked Nov 17 '10 06:11

Christopher


2 Answers

Use reorder:

Authors.books.reorder('name DESC')
like image 102
Ariejan Avatar answered Oct 21 '22 01:10

Ariejan


.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')
like image 23
Jon Avatar answered Oct 21 '22 00:10

Jon