LoginSignup
1
0

More than 3 years have passed since last update.

カラムの型をreferences型でマイグレーションする方法

Last updated at Posted at 2019-08-12

マイグレーションファイルの作成コマンド

Addカラム名テーブル名(複数形) カラム名:カラムの型
それぞれの頭文字は、大文字表示で書く。
例えばこのような書き方

$ rails g migration AddSalerRefToOrders saler:references

カラムの型をreferences型でマイグレーションする書き方は、以下のようになる。

class AddSalerRefToOrders < ActiveRecord::Migration[5.2]
  def change
    add_column :orders, :saler, :references, foreign_key: true
  end
end

add_columnの引数は4つあり、1つ目にカラムを追加するテーブル、2つ目に追加するカラム名、3つ目にカラムの型を指定する。また、オプションであるforeign_key: trueに部分は、任意の記載となる。

add_column :テーブル名(複数形), :カラム名, :カラムの型, オプション

<参考記事>
https://kossy-web-engineer.hatenablog.com/entry/2018/09/03/022121
https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/remove_column

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