3

How to create rails migration for auto calculated columns like below.

    a_column integer,
    b_column integer,
    total1 integer GENERATED ALWAYS AS (a_column+b_column) stored,
    total2 integer GENERATED ALWAYS AS (a_column-b_column) stored,
    total3 integer GENERATED ALWAYS AS (a_column/b_column) stored
); 

I don't want to do using Models, because I want to use same table from another system having different technology.

1 Answer 1

2

You can use pure SQL in migration

def up
  execute <<~SQL
    CREATE TABLE table_name (
      a_column integer,
      b_column integer,
      total1 integer GENERATED ALWAYS AS (a_column+b_column) stored,
      total2 integer GENERATED ALWAYS AS (a_column-b_column) stored,
      total3 integer GENERATED ALWAYS AS (a_column/b_column) stored
    );
  SQL
end

def down
  drop_table :table_name
end

When using such migrations, in order for the database schema to be correct, you need to use SQL dump type (default type is Ruby). To setup this setting add line to your config/application.rb

config.active_record.schema_format = :sql

After that schema will be saved to db/structure.sql

Please read more

Sign up to request clarification or add additional context in comments.

2 Comments

You should also change the schema dumps to SQL instead of schema.rb or the information will get lost or it might blow up. blog.appsignal.com/2020/01/15/…
Thanks @max. I added information to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.