Tet*_*yna 0 postgresql activerecord ruby-on-rails rails-migrations
我有一个表'Invoices',其中包含两个布尔列:
Table name: invoices
id :integer not null, primary key
...
sent :boolean default(FALSE)
payment_received :boolean default(FALSE)
Run Code Online (Sandbox Code Playgroud)
这两列定义了发票的状态:
def status
if sent & payment_received
:paid
elsif sent | payment_received
:sent
else
:created
end
end
Run Code Online (Sandbox Code Playgroud)
有一天,我们决定删除这些布尔列,并在Rails枚举的帮助下创建包含发票状态的新列
status :integer
enum status: [ :created, :sent, :paid ]
Run Code Online (Sandbox Code Playgroud)
所以现在我需要做三件事:
我怎样才能做到这一点?我可以在我的本地环境中轻松完成此任务,但我无法理解如何在生产服务器上执行此操作.例如,如果我将创建一个更新我的表的迁移和一个计算状态的rake任务,则迁移首先传递,我的数据将从布尔列中移除,然后才能使用它们.
注意:如果它以某种方式重要:我使用Postgres.
任何帮助表示赞赏!
小智 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |