How to override :order defined in a has_many

痴心易碎 提交于 2019-12-03 05:30:36

问题


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


回答1:


Use reorder:

Authors.books.reorder('name DESC')



回答2:


.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')



回答3:


Author.first.books.reverse_order


来源:https://stackoverflow.com/questions/4202097/how-to-override-order-defined-in-a-has-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!