Ruby on rails Rails 3“last”方法从ActiveRecord输出返回不正确的结果

Ruby on rails Rails 3“last”方法从ActiveRecord输出返回不正确的结果,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我的控制器中有以下代码: @items = Item.where(:user_id => 1).order("updated_at DESC").limit(2) @oldest_item = @items.last 出于某种原因,我猜这与我最近升级到Rails 3有关,@oldest\u item没有设置为@items中的最后一项,而是设置为与item匹配的最后一项。其中:user\u id=>1.orderupdated\u at DESC 因此,假设有3个匹配项,A、B和C。@it

我的控制器中有以下代码:

@items = Item.where(:user_id => 1).order("updated_at DESC").limit(2)
@oldest_item = @items.last
出于某种原因,我猜这与我最近升级到Rails 3有关,@oldest\u item没有设置为@items中的最后一项,而是设置为与item匹配的最后一项。其中:user\u id=>1.orderupdated\u at DESC

因此,假设有3个匹配项,A、B和C。@items被设置为[A、B],然后@oldest_item被设置为C

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

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


有人能解释一下这到底是怎么回事吗?

出于某种原因,ActiveRecord::Relation忽略了限制选项

在Rails3中,ActiveRecord在需要访问结果之前不会实际执行查询。调用last可以做到这一点,但再次忽略了限制

您可以通过调用查询中的all命令ActiveRecord执行查询。然后,当你最后一次运行时,它将为你提供你要查找的最后一张记录

@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"
对我来说,这似乎不是预期的行为。我把一个bug归档在数据库中


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

我正在使用Rails 6,并且有一个类似的问题。我在我的记录上使用从数据库重新加载它

account=account.new => account.id=1 帐户重新加载 Account Load 1.2ms选择accounts.*从accounts.id=$1 LIMIT 1[[id,1]] =>
您是否尝试过在控制器的两行之间插入一行调试器,运行ruby脚本/控制台,调用您的操作,然后深入查看发生了什么?你所做的似乎是对的。如果您这样做了:@oldest\u item=item.where:user\u id=>1.orderupdated\u at DESC.limit2.last这似乎是ActiveRecord中的一个bug。