从上次创造性地创建记录

时间:2017-02-01 10:57:34

标签: ruby-on-rails ruby

我需要从第三方API获取交易数据,并定期保存记录(每月一次)。这是一个例子:

class BalanceTransaction::Update
  include Service

  attr_reader :offset, :transactions

  def initialize(offset)
    @offset = offset
    @transactions = fetch_transactions
  end

  def call
    ActiveRecord::Base.transaction do
      transactions.auto_paging_each do |txn|
        type = txn[:type]
        source = txn[:source]
        case type
          when 'charge', 'adjustment'
            invoice = find_invoice(source)
            ac_id = invoice.account.id
            update_attrs(id: invoice.id, account_id: ac_id, type:'invoice', attrs: txn)
          when 'refund'
            refund = find_refund(source)
            ac_id = refund.invoice.account.id
            update_attrs(id: refund.id, account_id: ac_id, type:'refund', attrs: txn)
        end
      end
    end
    true
  end

  private

  def find_invoice(source)
    Invoice.find_by!(stripe_charge_id: source)
  end

  def find_refund(source)
    Refund.find_by!(stripe_refund_id: source)
  end

  def update_attrs(id:, account_id:, type:, attrs:)
    BalanceTransaction.create(
      account_id: account_id,
      stripe_transaction_id: attrs[:id],
      gross_amount: attrs[:amount],
      net_amount: attrs[:net],
      fee_amount: attrs[:fee],
      currency: attrs[:currency],
      transactionable_id: id,
      transactionable_type: type)
  end

  def fetch_transactions
    external_card_balance.all(limit: offset)
  rescue *EXTERNAL_CARD_ERRORS => e
    ExternalCardErrorHandler.new(e).handle
  end

  def external_card_balance
    Stripe::BalanceTransaction
  end
end

我想知道如何从上次有意识地批量插入。如果我发现偏移后创建的数据,我应该检查created_at并删除它们吗?你能给我一些建议吗?

1 个答案:

答案 0 :(得分:1)

交易是否具有唯一ID或任何可以使其唯一的字段?也许您可以使用validates_uniqueness_of来避免保存已经提取的交易。