首页 > 解决方案 > Rails 使用进程移除器的代码重构来加速数据库

问题描述

我的工人阶级移除了InquiryProcess早于x time(默认应设置为 6 个月)。可能这将是一个大数据规模,所以有没有机会用下面的代码加速删除?

class OldProcessRemover
  def initialize(date: 6.months.ago)
    @date = date
  end

  attr_reader :date

  def call
    remove_loan
    remove_checking_account
  end

  private

  def remove_loan
    loan_template = InquiryTemplate.find_by(inquiry_process_name: InquiryTemplate::LOAN_APPLICATION_PROCESS_NAME)
    loan_template.inquiry_processes.where('created_at <= ?', date).each(&:destroy)
  end

  def remove_checking_account
    checking_account_template = InquiryTemplate.find_by(
      inquiry_process_name: InquiryTemplate::CHECKING_ACCOUNT_OPENING_PROCESS_NAME,
    )
    checking_account_template.inquiry_processes.where('created_at <= ?', date).each(&:destroy)
  end
end

也许我可以使用的地方find_in_batches?我不认为这些方法是单一的责任,所以重构也会有所帮助。

标签: ruby-on-railsrubyrefactoring

解决方案


class OldProcessRemover
  def initialize(date: 6.months.ago)
    @date = date
  end

  attr_reader :date

  def call
    remove_loan
    remove_checking_account
  end

  private

  def remove_loan
    remove_processes!(InquiryTemplate::LOAN_APPLICATION_PROCESS_NAME)
  end

  def remove_checking_account
    remove_processes!(InquiryTemplate::CHECKING_ACCOUNT_OPENING_PROCESS_NAME)
  end

  def remove_processes!(process_name)
    account_template = InquiryTemplate.find_by(
      inquiry_process_name: process_name
    )
    account_template.inquiry_processes
                    .where('created_at <= ?', date)
                    .find_in_batches { |group| group.destroy_all }
  end
end

我认为 using.find_in_batches { |group| group.destroy_all }.find_each {|record| record.destroy }here 之间没有任何重大区别。


推荐阅读