Wil*_*nes 2 ruby-on-rails ruby-on-rails-3
我的控制器中有以下代码:
@items = Item.where(:user_id => 1).order("updated_at DESC").limit(2)
@oldest_item = @items.last
Run Code Online (Sandbox Code Playgroud)
出于某种原因,我猜这与我最近升级到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.
有人可以向我解释这里到底发生了什么事吗?
出于某种原因,ActiveRecord :: Relation忽略了该limit选项.
在Rails 3中,ActiveRecord实际上不会执行您的查询,直到需要访问结果.调用会这样做last(但同样,忽略了限制).
您可以通过调用查询来告诉ActiveRecord执行all查询.然后,当你运行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"
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎不是预期的行为.我在rails问题跟踪器中提交了一个错误.
更新:@BaroqueBobcat提交了一个被接受的补丁,因此应该在即将发布的Rails 3.1版本中修复.