How to format this PostgreSQL query to be able to run with db:migrate

Viewed 70

I want create the following table. I made it by running the SQL from ActiveRecord using

alter table items add column sumup numeric generated always as ( quantity * price + (quantity * price* fpa/100) ) stored;

Is that the proper way to do it?

  def change
    create_table :items do |t|
      t.string :itemName
      t.string :prom
      t.string :promCode
      t.string :baseCode
      t.string :desc
      t.numeric :fpa
      t.numeric :price
      t.integer :quantity
      t.string :monadaMe
      t.string :familys

      t.timestamps
    end
    ActiveRecord::Base.connection.execute(" alter table items add column sumup numeric generated always as ( quantity * price + (quantity * price* fpa/100) ) stored;")
  end
end
1 Answers

Create only the new column:

rails generate migration AddSumupToItems sumup:float

In your model, add:

before_save :calculate_sumup

def calculate_sumup
  sumup = ( quantity * price + (quantity * price* fpa/100) )
  self.sumup = sumup
end
Related