【问题标题】:How to format this PostgreSQL query to be able to run with db:migrate如何格式化此 PostgreSQL 查询以便能够与 db:migrate 一起运行
【发布时间】:2020-03-29 23:29:14
【问题描述】:

我想创建下表。我是通过使用 ActiveRecord 运行 SQL 来实现的

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

这是正确的做法吗?

  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

【问题讨论】:

标签: ruby-on-rails ruby postgresql


【解决方案1】:

只创建新列:

rails generate migration AddSumupToItems sumup:float

在您的model 中,添加:

before_save :calculate_sumup

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

【讨论】:

  • 我刚刚注意到一个错误,即当我更新表格价格时,总和仍然具有旧值..即使我更新,它们的工作方式也很好
猜你喜欢
  • 2018-04-11
  • 1970-01-01
  • 2021-10-25
  • 2019-09-16
  • 1970-01-01
  • 2022-01-17
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多