0
0

More than 1 year has passed since last update.

Railsでテーブル作成時にカラムの順番を指定する

Posted at

やりたいこと

MySQLの場合です。
SQLiteでもできるかも?(未検証)
PostgreSQLは少し面倒そう?https://wiki.postgresql.org/wiki/Alter_column_position/ja

Userテーブル作成時にdeleted_at等のカラムを作りたいとします。
作成後のschemaでは以下のようにupdated_atの後ろになって欲しい場合に、どうすれば良いか。

  create_table "users", force: :cascade do |t|
    t.string   "email",        limit: 255
    t.string   "name",         limit: 255
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.datetime "deleted_at" # updated_atの後ろ
  end

普通に作るとこうなってしまいます。
afterオプションも、普通につけるだけだと意味なしです。

  create_table "users", force: :cascade do |t|
    t.string   "email",        limit: 255
    t.string   "name",         limit: 255
    t.datetime "deleted_at" # updated_atの後ろにしたい
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

結論

こうすれば可能です。

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :name

      t.timestamps null: false
    end

    add_column :users, :deleted_at, :datetime, after: :updated_at
  end
end

補足

afterオプションは、create_tableメソッドにつけても効果なしです。
add_columnメソッドにつけないと効果がないので、
テーブル作成時のmigrationファイルに、create_tableメソッドとadd_columnメソッドを分けて記述すればOKです。

0
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
0
0