2
0

More than 1 year has passed since last update.

【Rails】後から id 列を追加したい

Posted at

id: false で作成したテーブルに対して、やっぱり id を追加したいってなることもありますよね。

そんなときは以下のマイグレーションで追加できます。

class AddIdToUsers < ActiveRecord::Migration[6.1]
  def change
    add_column :users, :id, :bigint, primary_key: true, auto_increment: true, null: false, first: true
  end
end

これで以下のようなマイグレーションが実行されます。

Migrating to AddIdToUsers (20230215062132)
== 20230215062132 AddIdToUsers: migrating =======================
-- add_column(:users, :id, :bigint, {:primary_key=>true, :auto_increment=>true, :null=>false, :first=>true})
   (54.6ms)  ALTER TABLE `users` ADD `id` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
   -> 0.0554s
== 20230215062132 AddIdToUsers: migrated (0.0555s) ==============

auto_increment で自動採番されるので、NOT NULL カラムとして追加できます。
また、 first: true 指定によって、先頭カラムとして追加できます。

これで、 id: false を指定せずにテーブル作成した場合と同じような感じになります。

動作確認環境

  • Rails: 6.1.7
  • MySQL: 5.7
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0