Rails 3“最后"方法从 ActiveRecord 输出返回不正确的结果 [英] Rails 3 "last" method is returning incorrect result from ActiveRecord output

查看:33
本文介绍了Rails 3“最后"方法从 ActiveRecord 输出返回不正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got the following code in my controller:

@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").

For some reason, and I'm guessing this has to do with my recent upgrade to Rails 3, @oldest_item is not being set to the last item in @items, but is instead being set to the last item that matches Item.where(:user_id => 1).order("updated_at DESC").

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

So imagine there are 3 items that match, A, B, and C. @items is being set to [A, B], and then @oldest_item is being set to C.

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

Oddly, when I call @items.last from within my view, it is properly returning B.

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

When I paste in the two lines from my controller into the console, it also properly returns B.

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

Can someone explain to me what the heck is going on here?

推荐答案

出于某种原因,ActiveRecord::Relation 忽略了 limit 选项.

For some reason, ActiveRecord::Relation is ignoring the limit option.

在 Rails 3 中,ActiveRecord 在需要访问结果之前不会实际执行您的查询.调用 last 可以做到这一点(但同样忽略了限制).

In Rails 3, ActiveRecord doesn't actually execute your query until need to access the results. Calling last does this (but again, ignores the limit).

您可以通过对查询调用 all 来告诉 ActiveRecord 执行查询.然后,当你运行 last 时,它会给你你正在寻找的最后"记录.

You can tell ActiveRecord to execute the query by calling all on your query. Then, when you run last on that, it'll give you the "last" record you're looking for.

@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 问题跟踪器中提交了一个错误.

This doesn't seem like expected behavior to me. I've filed a bug in the rails issues tracker.

更新:@BaroqueBobcat 提交了一个补丁接受,所以它应该在即将发布的 Rails 3.1 版本中修复.

Update: @BaroqueBobcat submitted a patch which got accepted, so it should be fixed in the upcoming 3.1 release of Rails.

这篇关于Rails 3“最后"方法从 ActiveRecord 输出返回不正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆