向現有資料新增 NOT NULL 約束

假設你要將外來鍵 company_id 新增到 users 表中,並且你希望對其具有 NOT NULL 約束。如果你已經在 users 中擁有資料,則必須分多步執行此操作。

class AddCompanyIdToUsers < ActiveRecord::Migration
  def up
    # add the column with NULL allowed
    add_column :users, :company_id, :integer

    # make sure every row has a value
    User.find_each do |user|
      # find the appropriate company record for the user
      # according to your business logic
      company = Company.first
      user.update!(company_id: company.id)
    end

    # add NOT NULL constraint
    change_column_null :users, :company_id, false
  end

  # Migrations that manipulate data must use up/down instead of change
  def down
    remove_column :users, :company_id
  end
end