向现有数据添加 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