Programming Journal

学習したことの整理用です。

【Rails】 default値の変更

ちょっと詰まったのでメモ フォーム入力画面でplaceholderを表示させたいけど、デフォルト値を設定していたため、表示できない

良し悪しは置いといて、default値を削除したい。

DBはMySQL Rails 6.0.3.4

試したけど、できなかったmigrationスクリプト

class ChangeUserProfileColumn < ActiveRecord::Migration[6.0]
  def up
    change_column :user_profiles, :age, :integer
    change_column :user_profiles, :job, :string, limit: 20
  end
  def down
    change_column :user_profiles, :age, :integer, default: 0
    change_column :user_profiles, :job, :string, default: '', limit: 20
  end
end
class ChangeUserProfileColumnDefault < ActiveRecord::Migration[6.0]
  def change
    change_column_default :user_profiles, :age, from: true, to: false
    change_column_default :user_profiles, :job, from: true, to: false
  end
end

成功したmigrationスクリプト

class ChangeUserProfileColumnDefault < ActiveRecord::Migration[6.0]
  def change
    change_column_default :user_profiles, :age, nil
    change_column_default :user_profiles, :job, nil
  end
end

change_column_default (ActiveRecord::ConnectionAdapters::SchemaStatements) - APIdock