LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

[いつか記事にするよう][自分用メモ]マイグレーションファイルについて 

Last updated at Posted at 2021-10-02

マイグレーションファイルの状態を確認するとき

rake db:migrate:status

既存カラムにdefaultオプションを追加する時

$ rails g migration change_column_default_to_users
class ChangeColumnDefaultToUsers < ActiveRecord::Migration[5.2]
  def change
    change_column_default :users, :name, from: nil, to: ""
  end
end
rails db:migrate

既存カラムにnull制約を追加する時

rails g migration change_colum_null_name_users
class ChangeColumDefaultNullUsers < ActiveRecord::Migration[6.1]
  def change
    change_column_null :users, :name, false, 0
  end
end
rails db:migrate

カラムの追加

rails g migration モデル名 カラム名:データ型
class ChangeColumnDefaultToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column_ :users, :モデル名, カラム名, : データ型
  end
end
rails db:migrate

カラムの編集

rails g migration ChangeDatetipeReferencetoposts
change_column :posts, :researcher_id, :references, foreign_key: true
rails db:migrate

モデルの紐付け

rails g migration  AddResearcherIdToPosts
def change
    execute 'DELETE FROM Posts;'
    add_reference :posts, :researcher, null: false, index: true
end

 デバッグ

already existsの場合

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