5
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails Migrationまとめ

5
Last updated at Posted at 2018-09-23

RailsのMigrationコマンドを自分用にまとめました。

モデル作成

$ rails generate model <モデル名単数形>
  • example
$ rails generate model ship

モデル修正

$ rails g migration Add<列名>To<モデル名> <列名>:<型>
$ rails db:migrate

列を追加したい例

  • User テーブルに locale 列を追加したい例
$ rails g migration AddLocaleToUser locale:string
$ rails db:migrate

参照関係を追加したい例

  • IssueComment テーブルにRoleモデルの参照関係(role列)を追加したい例
$ rails g migration AddRoleToIssueComment role:references
$ rails db:migrate

参照関係を追加したい例(外部キー制約を付けない場合)

def change
  add_reference :issue_comments, :role, foreign_key: false
end

列を削除したい例

  • User テーブルの列 locale を 削除したい例
$ rails g migration RemoveLocaleToUser locale
$ rails db:migrate

参照関係を削除したい例

  • IssueComment テーブルに role 列を削除したい例
def change
  remove_reference :issue_comments, :role, index: true, foreign_key: true
end

テーブル名を変更したい例

  • User テーブルの名前 users を hoge_users に変更したい例
def change
  rename_table :users, :hoge_users
end

列名を変更したい例

  • User テーブルの列 local の列名を locale に変更したい例
def change
  rename_column :users, :local, :locale # 列名をlocaleに変更
end

列の型を変更したい例

  • User テーブルの列 locale を text型 → string型 に変更したい例
def change
  change_column :users, :locale, :string
end

indexを追加したい例

  • Ship テーブルの列 ship_code にindex(Unique制約有)を付けたい場合
def change
  add_index :ships, :ship_code, :unique => true
end

indexを追加したい例(複数列)

  • ShipEquipment テーブルの列 ship_id,sfi,equipment_model_id にindex(Unique制約有)を付けたい場合
def change
  add_index :ship_equipments, [:ship_id, :sfi, :equipment_model_id], :unique => true
end

既にindexが存在するテーブルにUnique制約を付けたい例

def change
  remove_index :ship_equipments, [:ship_id, :sfi, :equipment_model_id]
  add_index :ship_equipments, [:ship_id, :sfi, :equipment_model_id], :unique => true
end

indexが長すぎるため、index名を付けたい例

def change
  add_index :satellite_speed_logs, [:ship_equipment_id, :measurement_date], name: :index_satellite_speed_logs_ship_equipment_measurement_date
end

モデル削除

def change
  drop_table :users
end

rollback

$ rails db:version # 現在のバージョンの確認
Current version: 20180816060332
$ rails db:rollback # 1つ前に戻す
$ rails db:rollback STEP=2 # 2つ前に戻す

DBの再構築

$ rails db:reset
# すべてのテーブルをdrop
# "db/schema.rb" を元にテーブルを再作成
5
15
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
5
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?