gpt4 book ai didi

ruby-on-rails - 将数据从已删除的列移动到刚刚在 Rails 迁移中创建的列

转载 作者:行者123 更新时间:2023-11-29 14:06:40 25 4
gpt4 key购买 nike

我有一个“发票”表,其中包含两个 bool 列:

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 枚举的帮助下,决定删除这些 bool 列并创建将包含发票状态的新列

status :integer

enum status: [ :created, :sent, :paid ]

所以现在我需要做三件事:

  1. 添加新列“状态”
  2. 计算现有发票的状态,更新状态列
  3. 删除“已发送”和“payment_received”列。

我该怎么做?我可以在本地环境中轻松完成此任务,但我不明白如何在生产服务器上执行此操作。例如,如果我将创建一个更新我的表的迁移和一个计算状态的 rake 任务,迁移首先通过并且我的 bool 列中的数据将在我可以使用它们之前被删除。

注意:如果这很重要:我使用 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

关于ruby-on-rails - 将数据从已删除的列移动到刚刚在 Rails 迁移中创建的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com