This is a backport of the generated column support that was added to Rails 7: rails/rails#41856
It also includes fixes from two other PRs: I also pulled in changes from two other related PRs: rails/rails#43263 rails/rails#44319
Much thanks and appreciation to everyone who worked on the generated columns support PRs. ❤️🎉
NOTE: Generated columns are supported since version 12.0 of PostgreSQL.
# db/migrate/20131220144913_create_users.rb
create_table :users do |t|
t.string :name
t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true
end
# app/models/user.rb
class User < ApplicationRecord
end
# Usage
user = User.create(name: 'John')
User.last.name_upcased # => "JOHN"
Add this line to your application's Gemfile:
gem 'pg_generated_column_support'
And then execute:
$ bundle
Or install it yourself as:
$ gem install pg_generated_column_support
The gem is available as open source under the terms of the MIT License.