2013-03-01 77 views
0

Rails tutorial中,它说我可以简单地使用.order("something"),它会工作。然而,当我写Course.order("name DESC")我得到查询:在Rails中添加自己的订单

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

当我真正想要的(请注意,它只是通过name DESC订购):

SELECT "courses".* FROM "courses" ORDER BY name DESC

我怎么会迫使它通过?

+2

查看您的应用/ models/order.rb。你有什么叫做“default_scope”? – 2013-03-01 04:28:22

+0

是的,我如何覆盖它?它说'default_scope:order =>'name ASC'' – Hengjie 2013-03-01 04:29:12

+2

Yuck! :-)那么你可以使用“with_exclusive_scope”覆盖它。但最好不要首先使用default_scope。 – 2013-03-01 04:32:28

回答

2

这是因为我在造成它的模型中使用了default_scope。运行此避免了作用域:

Course.unscoped.order("name DESC")

编辑:以供将来参考,这是代码味道和default_scope应谨慎使用,因为往往开发商会忘记(编写代码个月后),其default_scope设置和咬你回来。

+0

是'.unscoped'是要走的路。 – 2013-03-01 04:34:13

4

,如果你有一个default_scope befined默认顺序,您可以通过使用reorder

Order.reorder('name DESC') 

更新替代:用unscoped也可以工作,但要警惕,这完全消除了对查询中定义的所有范围。例如,以下将全部返回相同的sql

Order.where('id IS NOT NULL').unscoped.order('name DESC') 
Order.unscoped.order('name DESC') 
Order.scope1.scope2.unscoped.order('name DESC') 
current_user.orders.unscoped.order('name DESC') 
+0

谁低估,请解释原因。我看到这里没有问题。 – 2013-03-01 04:36:09

+0

想知道为什么这得到了downvote。 – jvnill 2013-03-01 04:37:11

+0

不幸的是,甚至没有版主可以看到投票历史记录(我不是一个国防部),但它是相当粗鲁的downvote一个非明显的情况下没有解释。耸耸肩,我猜。 – 2013-03-01 04:52:25