Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

akira-hamada
Webエンジニア。主にRuby。好きなエディタ: Vim
http://akira-hamada.github.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした