加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 相当于foo_ids的find_each?

发布时间:2020-12-17 02:23:39 所属栏目:百科 来源:网络整理
导读:鉴于此模型: class User ActiveRecord::Base has_many :thingsend 然后我们可以这样做:: @user = User.find(123)@user.things.find_each{ |t| print t.name }@user.thing_ids.each{ |id| print id } 有很多@ user.things,我想只批量遍历它们的id,就像find_e
鉴于此模型:

class User < ActiveRecord::Base
  has_many :things
end

然后我们可以这样做::

@user = User.find(123)
@user.things.find_each{ |t| print t.name }
@user.thing_ids.each{ |id| print id }

有很多@ user.things,我想只批量遍历它们的id,就像find_each一样.有没有方便的方法来做到这一点?

目标是:

>不要立即将整个thing_ids数组加载到内存中
>仍然只加载thing_ids数组,而不是为每个id实例化Thing

解决方法

Rails 5引入了 in_batches方法,它产生一个关系并在内部使用pluck(primary_key).我们可以利用关系的 where_values_hash方法来检索已经拔出的id:

@user.things.in_batches { |batch_rel| p batch_rel.where_values_hash['id'] }

请注意,in_batches具有与find_each类似的顺序和限制限制.

这种方法有点hacky,因为它取决于in_batches的内部实现,如果in_batches在将来停止采集id,则会失败.非hacky方法是batch_rel.pluck(:id),但这会运行相同的pluck查询两次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读