LoginSignup
0
0

More than 1 year has passed since last update.

Rails 後からNot null 制約を付与する

Posted at

テーブルのカラムに、後からNot null 制約をつける手順を書いていきます。

まず、新たに Not null 制約を付与するためのマイグレーションファイルを作成します。

rails g migration ChangeCloumnsNotnullAddテーブル名

# rails g migration ChangeCloumnsNotnullAddMovies

マイグレーションファイルを作成

db/migrate/***_change_columns_add_notnull_on_movies.rb
class ChangeCloumnsNotnullAddMovies < ActiveRecord::Migration[6.0]
  def change
    change_column :users, :title, :string, null: false
    change_column :users, :image, :string, null: false
    change_column :users, :released_year, :string, null: false
    change_column :users, :country, :string, null: false
    change_column :users, :screening_time, :string, null: false
    change_column :users, :synposis, :string, null: false
  end
end

null: falseで制約を付与します
null: trueで制約を付与しません

# rails db:migrate

するとエラーが、、、

# rails db:migrate
== 20220414030927 ChangeCloumnsNotnullAddMovies: migrating ====================
-- change_column(:movies, :title, :string, {:null=>false})
rails aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Invalid use of NULL value

どうやら既に作ってあるmovieデータの中に、titleに何も指定されてない(nullになっている)ものがあり、このままだとtitleカラムはNot nullにできないということですね。

titleがnullになっているデータがないか確認してみます。

# rails c


> movies = Movie.all

> movies.find(6)

一つずつmovies.findで確認してみたところ、movie(id:6)のデータのtitleがnullになっていました。なのであとはこれを消すだけです。

> Movie.find(6).destroy

無事rails db:migrateを実行できて、not null制約を付与することができました!

参考:https://qiita.com/pank24ever/items/b411fe0a238aadc03fb0

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