Last active
December 30, 2021 08:20
-
-
Save tejasbubane/88e504513a4d42afacde86f3194fc040 to your computer and use it in GitHub Desktop.
Postgres generated columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Read the blog: https://tejasbubane.github.io/posts/2021-12-18-rails-7-postgres-generated-columns/ | |
require "bundler/inline" | |
gemfile(true) do | |
source "https://rubygems.org" | |
# Activate the gem you are reporting the issue against. | |
gem "activerecord", "~> 7.0.0" | |
gem "pg", "~> 1.2.3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
ActiveRecord::Base.establish_connection( | |
adapter: 'postgresql', | |
database: 'generated_columns', | |
host: 'localhost', | |
port: '5432', | |
username: 'tejas', | |
password: '', | |
pool: '5' | |
) | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :orders, force: true do |t| | |
t.integer :user_id | |
t.decimal :price, precision: 8, scale: 2 | |
t.decimal :tax, precision: 8, scale: 2 | |
t.virtual :total, type: :decimal, as: 'price + tax', stored: true | |
end | |
end | |
class Order < ActiveRecord::Base | |
end | |
class FeatureTest < Minitest::Test | |
def test_total | |
# create | |
order = Order.create!(user_id: 1, price: 120, tax: 10) | |
order.reload | |
assert_equal 130, order.total | |
# update price | |
order.update(price: 130) | |
order.reload | |
assert_equal 140, order.total | |
# update tax | |
order.update(tax: 20) | |
order.reload | |
assert_equal 150, order.total | |
# run queries | |
Order.create!(user_id: 1, price: 50, tax: 20) | |
Order.create!(user_id: 1, price: 11, tax: 2) | |
Order.create!(user_id: 1, price: 1120, tax: 90) | |
Order.create!(user_id: 1, price: 80, tax: 20) | |
assert_equal 3, Order.where("total >= ?", 100).count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment