Rails通过进程重构的代码重构加速数据库

问题描述 投票:0回答:1

我有一个工人班级,该班级删除的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-rails ruby refactoring
1个回答
0
投票
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

我认为在这里使用.find_in_batches { |group| group.destroy_all }.find_each {|record| record.destroy }之间没有什么主要区别。

© www.soinside.com 2019 - 2024. All rights reserved.