1
0

More than 1 year has passed since last update.

Railsでカラムにnull制約を後から設定する

Posted at

目的

Postテーブルにある既存のtitleカラムにnull:falseを追加すること

設定方法

migartionファイルの作成

$ rails g migration ChangePresenseTitleOfPosts

create    db/migrate/20221008061033_change_presense_title_of_posts.rb

migrationファイル追記

20221008061033_change_presense_title_of_posts.rb
class ChangePresenseTitleOfPosts < ActiveRecord::Migration[7.0]
  def change
    change_column :posts, :title, :string, null: false
  end
end

データベース反映

rails db:migrate

まとめ

書き方としては

change_column :テーブル名, :カラム名, :データ型, null: false

今回説明した上記の方法(change_columnメソッド)だけではなくて、change_column_nullメソッドでの方法(下記のリンク)もあります。
https://railsdoc.com/page/change_column_null

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