LoginSignup
130
96

More than 5 years have passed since last update.

railsのmigrationで追加するカラムの順番をコントロールする

Posted at

railsで既に存在するテーブルにカラムを追加する時に、カラムの並びをコントロールしたいというお話


テーブル例

以下のようなテーブルがあって、更にmobile_phoneカラムを追加する場合。

schema.rb
  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
    t.string   "phone"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

以下のようなマイグレーションファイルでmobile_phoneカラム追加することになると思います。
しかし、これだとmobile_phoneカラムは最後に追加されてしまう。rails consoleやsequel proで見た時にphoneカラムとmobile_phoneカラムが離れちゃって見難い。

migration_file.rb
class AddMobilePhoneToUsers < ActiveRecord::Migration
  def change
    add_column :users, :mobile_phone, :string
  end
end

解決策

以下のように add_columnメソッドにafterオプションを指定してあげると、phoneカラムの隣にmobile_phoneカラムが追加される。

migration_file.rb
class AddMobilePhoneToUsers < ActiveRecord::Migration
  def change
    add_column :users, :mobile_phone, :string, after: :phone
  end
end

参考URL

130
96
2

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
130
96