Rails 7 now introduces support for generated columns with Postgres


PostgreSQL 12 comes with a new feature called generated columns. While other databases (particularly MySQL) have had this for a while now (called virtual or computed columns), Postgres just announced it! Unfortunately, it’s taken even longer for Rails to integrate it, until now!

A generated column is like a view but for columns instead. It is a “virtual” column meaning that it can not be written directly rather its value is dependent on another column. Let’s look at an example.

CREATE TABLE people (
  ...,
  height_cm numeric,
  height_in numeric GENERATED ALWAYS AS (height_cm / 2.54) STORED
);

height_in is now a generated column whose value is dependent on the height_cm column via the (height_cm / 2.54) relationship. The keyword STORED indicates if the generated column should be persisted to memory or VIRTUAL (computed on reading).

Before

Though Rails had support for MySQL virtual columns, nothing similar existed for its Postgres counterpart.

After

Rails now supports PostgreSQL generated columns! The syntax is intuitive and easy to implement.

create_table :users do |t|
  t.numeric :height_cm
  t.virtual :height_in, type: :numeric, as: 'height_cm / 2.54', stored: true
end

Now, height_in can be accessed as a normal ActiveRecord attribute, the only difference is that it does not support direct write operations.

Join Our Newsletter