2012-08-17 62 views
1

我有問題使用ActiveRecord按日期排序帖子......它沒有做我期望的。Rails發佈日期排序問題

1.9.3p194 :019 > Post.all(:select => [:id, :updated_at], :order => "updated_at DESC") 
    Post Load (0.7ms) SELECT id, updated_at FROM "posts" ORDER BY published_at DESC, updated_at DESC 
+----+---------------------------+ 
| id | updated_at    | 
+----+---------------------------+ 
| 22 | 2012-08-16 18:59:28 -0600 | 
| 9 | 2012-08-16 18:58:16 -0600 | 
| 11 | 2012-08-15 20:18:53 -0600 | 
| 1 | 2012-08-15 20:18:52 -0600 | 
| 12 | 2012-08-15 20:18:53 -0600 | 
| 6 | 2012-08-15 20:18:52 -0600 | 
| 13 | 2012-08-15 20:18:53 -0600 | 
| 2 | 2012-08-15 20:18:52 -0600 | 
| 15 | 2012-08-15 20:18:53 -0600 | 
| 5 | 2012-08-16 21:49:14 -0600 | 
| 17 | 2012-08-15 20:18:53 -0600 | 
| 4 | 2012-08-15 20:18:52 -0600 | 
| 20 | 2012-08-15 20:18:53 -0600 | 
| 7 | 2012-08-15 20:18:52 -0600 | 
| 21 | 2012-08-15 20:18:53 -0600 | 
| 14 | 2012-08-15 20:18:53 -0600 | 
| 10 | 2012-08-15 20:18:53 -0600 | 
| 8 | 2012-08-15 20:18:53 -0600 | 
| 19 | 2012-08-15 20:18:53 -0600 | 
| 18 | 2012-08-15 20:18:53 -0600 | 
| 16 | 2012-08-15 20:18:53 -0600 | 
| 3 | 2012-08-15 20:18:52 -0600 | 
+----+---------------------------+ 

請注意,#5有一個更新日期爲8月16日,但它不會到頂部!請注意,Rails似乎正確地排序它....

1.9.3p194 :020 > Post.all(:select => [:id, :updated_at], :order => "updated_at DESC").sort_by &:updated_at 
    Post Load (0.6ms) SELECT id, updated_at FROM "posts" ORDER BY published_at DESC, updated_at DESC 
+----+---------------------------+ 
| id | updated_at    | 
+----+---------------------------+ 
| 1 | 2012-08-15 20:18:52 -0600 | 
| 2 | 2012-08-15 20:18:52 -0600 | 
| 3 | 2012-08-15 20:18:52 -0600 | 
| 4 | 2012-08-15 20:18:52 -0600 | 
| 6 | 2012-08-15 20:18:52 -0600 | 
| 7 | 2012-08-15 20:18:52 -0600 | 
| 8 | 2012-08-15 20:18:53 -0600 | 
| 10 | 2012-08-15 20:18:53 -0600 | 
| 11 | 2012-08-15 20:18:53 -0600 | 
| 12 | 2012-08-15 20:18:53 -0600 | 
| 13 | 2012-08-15 20:18:53 -0600 | 
| 14 | 2012-08-15 20:18:53 -0600 | 
| 15 | 2012-08-15 20:18:53 -0600 | 
| 16 | 2012-08-15 20:18:53 -0600 | 
| 17 | 2012-08-15 20:18:53 -0600 | 
| 18 | 2012-08-15 20:18:53 -0600 | 
| 19 | 2012-08-15 20:18:53 -0600 | 
| 20 | 2012-08-15 20:18:53 -0600 | 
| 21 | 2012-08-15 20:18:53 -0600 | 
| 9 | 2012-08-16 18:58:16 -0600 | 
| 22 | 2012-08-16 18:59:28 -0600 | 
| 5 | 2012-08-16 21:49:14 -0600 | 
+----+---------------------------+ 

我敢肯定這是簡單的東西...任何幫助,你可以提供將不勝感激。

我已經試過這些都無濟於事:

Post.all(:order => "updated_at DESC") 
Post.all(:order => "updated_at DESC").limit(1) 
+1

您是如何得到這些漂亮的打印表格的? – megas 2012-08-17 04:00:40

+1

Hirb - 在控制檯中輸出結果很好的寶石。 – Brandon 2012-08-17 04:05:45

回答

1

想我已經想通了....我有「created_at」我認爲這是我擰了一個默認的範圍。

1

那麼,SQL絕對是不正確的。

SELECT id, updated_at FROM "posts" ORDER BY published_at DESC, updated_at DESC 

應該

SELECT id, updated_at FROM "posts" ORDER BY updated_at DESC 

編輯:

是,默認的範圍意味着它將通過兩種published_at和的updated_at訂購。如果要在模型中保留默認範圍,但不使用此查詢的範圍,則可以使用:

Post.unscoped.all(:select => [:id, :updated_at], :order => "updated_at DESC")