【问题标题】:Move data from removed column to just created one in Rails migration在 Rails 迁移中将数据从已删除的列移动到刚刚创建的列
【发布时间】:2016-05-11 05:37:04
【问题描述】:

我有一个包含两个布尔列的“发票”表:

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 ]

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

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

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

注意:如果它很重要:我使用 Postgres。

感谢任何帮助!

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord rails-migrations


    【解决方案1】:

    尝试以下迁移。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多