💎Rails tip: PostgreSQL generated columns

Sebastien Auriault
Mar 5, 2022
Did you know Rails 7 added support for PostgreSQL generated columns? These columns will be calculated by the database only once on INSERT and UPDATE.

# db/migrate/20220226153929_create_orders.rb
class CreateOrders < ActiveRecord::Migration[7.0]
  def change
    create_table :orders do |t|
      t.integer :subtotal_cents
      t.integer :tax_cents
      t.virtual :total_cents, type: :integer, as: "subtotal_cents + tax_cents", stored: true
      
      t.timestamps
    end
  end
end

# console
Order.create(subtotal_cents: 1000, tax_cents: 200)
Order.last.total_cents # => 1200