Rails find_each with order 的问题

vkill · 2012年03月04日 · 最后由 lainuo 回复于 2012年03月04日 · 4478 次阅读

因为是在 order 后使用 find_each ,但是 find_each 还是会强制使用 id 排序,请问下这个如何解决呢?

User.order("RAND()").find_each{|x| p x.id}
1
2
3
4
5
6

raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present?
#something
relation = relation.reorder(batch_order).limit(batch_size)

这个 batch_order 默认是 `id ASC`

怎么重置这个呢?或临时修改下呢?

find_each 没法用 order 和 limit 的,order 后直接 each 不行么,如果要指定批量大小的话,就自己在外面再加一层 find_in_batches

找到了个方法,太暴力,得重新弄弄

module ActiveRecord
  module Batches
    def batch_order
      "#{quoted_table_name}.#{quoted_primary_key} DESC"
    end
  end
end

#1 楼 @lainuo 没用的,限制 不能 order 和 limit 是 在 find_in_batches 里的,所以外面套一个没用,还有用 find_each 就是因为数据太多,用 each 也就没意义了

@vkill find_in_batches 的 yield 的 block 里是 Array 啊,直接操作这个 Array 不行么?

#4 楼 @lainuo 因为我要先 order 再 find_each,按照 order 的排序来更新每个 record 的排名字段,所以无效

@vkill 我还是没明白,先找出来再排序不是一样么。

@lainuo 我有 1w 条记录,我要对这 1w 条记录进行一个总排序 还有 find_each 后无法排序吧?

@vkill find_each yield 的是单条记录,find_in_batches 是整个数据集

我指是排序不是指数据库层面的,是想说找出来后再对这个数据集进行排序。

@lainuo find_in_batches 返回的是 array,也就是仅'1000'条记录,所以不是我想要的

@vkill 你可以指定 :batch_size 这个参数

@lainuo 如果用 :batch_size 那和直接用 each 有啥区别呢? 看下 find_in_batches 最后一句

records = relation.where(table[primary_key].gt(primary_key_offset)).to_a

@vkill 额...那直接 limit 就行了嘛....find_each也是一条条去 yield, 和 each 也一样...

maxchen Active Record order: ("created_at DESC") 不成功 提及了此话题。 02月26日 09:50
需要 登录 后方可回复, 如果你还没有账号请 注册新账号