2011-05-03 60 views
1

我有下面的代碼在我的控制器返回不正確的結果:Rails 3中的「最後」的方法是從ActiveRecord的輸出

@items = Item.where(:user_id => 1).order("updated_at DESC").limit(2) 
@oldest_item = @items.last 

出於某種原因,我猜這是與我最近做的升級到Rails 3,@oldest_item未被設置爲@items中的最後一項,而是被設置爲與Item.where(:user_id => 1).order("updated_at DESC")匹配的最後一項。

所以,想象有相匹配的3個項目中,A,B,和C. @items被設置爲[A,B],然後@oldest_item被設置爲C.

奇怪的是,當我從叫我@items.last視圖中,它正確返回B.

當我從我的控制器兩行到控制檯粘貼,也適當地返回B.

有人能向我解釋到底是什麼去這裏?

+0

您是否曾嘗試在您的控制器中的兩行之間放置一個「調試器」行,並運行一個「ruby腳本/控制檯」,調用您的操作,並深入瞭解發生了什麼?你在做什麼似乎是對的。如果你這樣做:@oldest_item = Item.where(:user_id => 1).order(「updated_at DESC」)。limit(2).last – jefflunt 2011-05-03 01:12:08

回答

5

由於某種原因,ActiveRecord :: Relation忽略limit選項。

在Rails 3中,ActiveRecord實際上並沒有執行你的查詢,直到需要訪問結果爲止。調用last這樣做(但是再次忽略限制)。

您可以通過在您的查詢中調用all來告訴ActiveRecord執行查詢。然後,當您運行last時,它會爲您提供您要查找的「最後」記錄。

@items = Item.where(:user_id => 1).order("updated_at DESC").limit(2) 
# @items is an ActiveRecord::Relation here 
@oldest_item = @items.last 
# Returns "C" instead of "B". This is actually ignoring the `limit` parameter 

@items = Item.where(:user_id => 1).order("updated_at DESC").limit(2).all 
# @items is an Array of ActiveRecord objects here 
@oldest_item = @items.last 
# Returns "B" 

這似乎不像我預期的行爲。我在rails issues tracker中提交了一個錯誤。

更新:@BaroqueBobcat提交了一個patch已被接受,所以它應該在即將發佈的3.1版Rails中得到修復。

+0

這看起來像是ActiveRecord中的一個錯誤。 – 2011-05-03 02:17:25

+0

我已經爲此提交了一個錯誤報告。 https://github.com/rails/rails/issues/371 – 2011-05-03 03:01:01

相關問題