Rails 3“last”方法从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")的最后一项Item.where(:user_id => 1).order("updated_at DESC")

所以想象有3个项目匹配,A,B和C. @items被设置为[A,B],然后@oldest_item被设置为C.

奇怪的是,当我从我的视图中调用@items.last时,它正在返回B.

当我从控制器中将两行粘贴到控制台时,它也正确地返回B.

有人可以向我解释这里到底发生了什么事吗?

出于某种原因,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问题跟踪器中提交了一个错误。

更新 :@BaroqueBobcat提交了一个被接受的补丁 ,因此应该在即将发布的Rails 3.1版本中修复。