>我有一个表"发票",其中包含两个布尔列:
Table name: invoices
id :integer not null, primary key
...
sent :boolean default(FALSE)
payment_received :boolean default(FALSE)
这两列定义发票的状态:
def status
if sent & payment_received
:paid
elsif sent | payment_received
:sent
else
:created
end
end
有一天,在 Rails enum 的帮助下删除这些布尔列并创建新列以包含发票状态
status :integer
enum status: [ :created, :sent, :paid ]
所以现在我需要做 3 件事:
- 添加新列"状态"
- 计算现有发票的状态,更新状态列
- 删除"已发送"和"payment_received"列。
我该怎么做?我可以在本地环境中轻松完成此任务,但我无法理解如何在生产服务器上执行此操作。例如,如果我要创建一个更新表的迁移和一个计算状态的 rake 任务,则迁移首先通过,并且布尔列中的数据将被删除,然后才能使用它们。
注意:如果以某种方式很重要:我使用Postgres。
任何帮助不胜感激!
尝试以下迁移。
class UpdateInvoicesTable < ActiveRecord::Migration
def self.up
add_column :invoices,:status,:string
Invoice.find_in_batches(batch_size: 2000) do |invoices|
invoices.each do |invoice|
if invoice.sent & invoice.payment_received
invoice.status = 'paid'
elsif invoice.sent | invoice.payment_received
invoice.status = 'sent'
else
invoice.status = 'created'
end
invoice.save
end
end
remove_column :invoices,:sent
remove_column :invoices,:payment_received
end
end