小编sco*_*rix的帖子

在 Rails 中使用插入查询循环大数据的最佳方法是什么

我必须插入大数据,比如说 20k,我怀疑我是否编写了优化查询。

它能做什么:

  1. 使用满足某些条件的 sql 获取用户记录,它在 merge_user_records 的活动记录数组中获取超过 1k-20k 个用户
  2. 从 1k-20k 用户的 activerecord 数组中批量切片 100 个用户
  3. 循环遍历 merge_user 记录并从 merge_user_records 中的用户模型 user user_id 中查找用户
  4. 仍在循环中,用户调用方法construct_user_notifications来为每个用户插入user_notifications。
  5. 仍在循环中查找用户的设备。
  6. 在设备中运行循环以在每个设备上发送推送通知。
  7. 循环结束

这是代码。

merge_users = MergeField.get_user_field_values(notification_template.merge_field, scope_users) #=> **returns users 1k - 20k**
if merge_users.present?
  merge_users.each_slice(100) do |record|
    record.each do |user_record|
      user = User.find_by(id: user_record.user_id)
      text = notification_template.title
      notification_template.description = MustacheDescription.render(notification_template, user_record)
      text += " " + notification_template.description
      Rails.logger.info "Merge field message: #{notification_template.description}"
      construct_user_notifications(notification_template, user_record.user_id) #=> **this calls another method below which actually …
Run Code Online (Sandbox Code Playgroud)

ruby activerecord ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

1
推荐指数
1
解决办法
2556
查看次数