我有一个表'Invoices',其中包含两个布尔列:
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枚举的帮助下创建包含发票状态的新列
status :integer
enum status: [ :created, :sent, :paid ]
所以现在我需要做三件事:
我该怎么做?我可以在我的本地环境中轻松完成此任务,但我无法理解如何在生产服务器上执行此操作。例如,如果我将创建一个更新我的表的迁移和一个计算状态的rake任务,则迁移首先传递,我的数据将从布尔列中移除,然后才能使用它们。
注意:如果以某种方式重要:我使用Postgres。
感谢任何帮助!
答案 0 :(得分:5)
尝试以下迁移。
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