Cannot use column reference in DEFAULT expression rails migration

916 views Asked by At

Error : PG::FeatureNotSupported: ERROR: cannot use column reference in DEFAULT expression LINE 1: ..._at" timestamp, "total" decimal DEFAULT (COALESCE(price, (0)...

class AddTotalToOrderLines < ActiveRecord::Migration[6.1]
def up
  execute <<~SQL
    ALTER TABLE order_lines
    ADD COLUMN total numeric GENERATED ALWAYS AS (COALESCE(price, 0) * 
    COALESCE(quantity, 0)) STORED;
  SQL
end
2

There are 2 answers

3
elliotcm On

In case you thought you were going crazy (or some googler finds this), the issue is Rails converts a GENERATED column statement to a DEFAULT one if you're using schema.rb. In order to get it to behave you need to switch over to the structure.sql approach.

0
smathy On

Maybe you have another migration that's actually generating the error. The one you're showing there isn't :)