Back to Practice

Practice · Payments · Card 6

Wallet balance: balance column or ledger?

Users hold store credit. Many small credits and debits. Two reasonable shapes. The right one depends on what you'll need to ask.

The choice

Two candidate schemas, both valid Rails.

# Option 1: balance column
class User < ApplicationRecord
  # users.wallet_balance_cents
  def credit!(amount, source:)
    increment!(:wallet_balance_cents, amount)
  end
  def debit!(amount, source:)
    decrement!(:wallet_balance_cents, amount)
  end
end

# Option 2: ledger
class LedgerEntry < ApplicationRecord
  # ledger_entries.user_id, .amount_cents, .kind, .source_type, .source_id
end
class User < ApplicationRecord
  has_many :ledger_entries
  def wallet_balance_cents
    ledger_entries.sum(:amount_cents)
  end
end

The question

When does the balance-column shape break, and when is the ledger the obvious choice?

Take a moment. The balance column is simpler. The ledger is more correct. What does "more correct" buy you, and when does the cost of the SUM matter?