From 43c6e08b34452b217b7d2cc920f2e84dd8695a76 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 30 Jan 2025 23:10:23 -0600 Subject: [PATCH] Add Add A Generated Column To A PostgreSQL Table as a Rails TIL --- README.md | 3 ++- ...-generated-column-to-a-postgresql-table.md | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 rails/add-a-generated-column-to-a-postgresql-table.md diff --git a/README.md b/README.md index 0412a6a..dbfc16e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1579 TILs and counting..._ +_1580 TILs and counting..._ See some of the other learning resources I work on: - [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators) @@ -946,6 +946,7 @@ See some of the other learning resources I work on: - [Add A Check Constraint To A Table](rails/add-a-check-constraint-to-a-table.md) - [Add A Database Index If It Does Not Already Exist](rails/add-a-database-index-if-it-does-not-already-exist.md) - [Add A Foreign Key Reference To A Table](rails/add-a-foreign-key-reference-to-a-table.md) +- [Add A Generated Column To A PostgreSQL Table](rails/add-a-generated-column-to-a-postgresql-table.md) - [Add A Reference Column With An Index](rails/add-a-reference-column-with-an-index.md) - [Add ActiveRecord Error Not Tied To Any Attribute](rails/add-activerecord-error-not-tied-to-any-attribute.md) - [Add React With Webpacker To A New Rails App](rails/add-react-with-webpacker-to-a-new-rails-app.md) diff --git a/rails/add-a-generated-column-to-a-postgresql-table.md b/rails/add-a-generated-column-to-a-postgresql-table.md new file mode 100644 index 0000000..4b14846 --- /dev/null +++ b/rails/add-a-generated-column-to-a-postgresql-table.md @@ -0,0 +1,22 @@ +# Add A Generated Column To A PostgreSQL Table + +As of Rails 7, ActiveRecord supports generated columns for app's backed by a +PostgreSQL database. This is achieved with a `virtual` column. + +```ruby +class CreateTags < ActiveRecord::Migration[8.0] + def change + create_table :tags, id: :bigint do |t| + t.string :value + t.virtual :normalized_value, type: :text, as: "lower(value)", stored: true + + t.timestamps + end + end +end +``` + +With a table like this, any time we add a record with a `value`, PostgreSQL +computes and stores the `normalized_value` column based on that. + +[source](https://blog.saeloun.com/2022/01/25/rails-7-postgres-support-for-generated-columns/)