LoginSignup
0
1

More than 3 years have passed since last update.

【Rails】特定のカラムのオプションだけを変更したい

Posted at

Rails6.0.0でアプリを作っていて、既に作成済みのテーブルのカラムにオプションの制約をつけ忘れていた。
なので、特定のカラムのオプションだけを追加で設定する方法をまとめる。

現状

現状のマイグレーションファイルは以下のように「null:false」オプションを付け忘れているカラムがある。

class CreateItems < ActiveRecord::Migration[6.0]
  def change
    create_table :items do |t|
      t.string     :name
      t.text       :explain
      t.integer    :price
      t.references :user,            null: false, foreign_key: true
      t.integer    :category_id,     null: false
      t.integer    :item_status_id,  null: false
      t.integer    :shipping_fee_id, null: false
      t.integer    :prefecture_id,   null: false
      t.integer    :delivery_id,     null: false
      t.timestamps
    end
  end
end

手順

①新しいマイグレーションファイルを作る。

「rails g migration ChangeColumnOfItems」とコマンドを打つ(アッパーキャメル)。
コマンドの意味は「Itemsテーブルのカラムを変更せよ」という感じ。

terashimatakaya@MacBook-Air furima-34501 % rails g migration ChangeColumnOfItems
Running via Spring preloader in process 8220
      invoke  active_record
      create    db/migrate/20210220012237_change_column_of_items.rb

②マイグレーションファイルを自分で修正する。

「Railsガイドv6.1」のマイグレーションの章を参考に、以下のように記述した。
意味としては、「itemsテーブルのnameカラムにnull:falseのオプションを追加してね」という感じ。

class ChangeColumnOfItems < ActiveRecord::Migration[6.0]
  def change
    change_column_null :items, :name, false
    change_column_null :items, :explain, false
    change_column_null :items, :price, false
  end
end

③マイグレーションを実行

「rails db:migrate」を実行。

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