Techioz Blog

Rails が null を許可すべきでない場合に許可する

概要

class CreateProducts < ActiveRecord::Migration[7.0]
  def change
    create_table :products do |t|
      t.string :name
      t.string :code
      t.integer :gtin
      t.references :supplier, null: false, foreign_key: true
      t.references :group, null: false, foreign_key: true

      t.timestamps
    end
  end
end

テーブル製品を作成すると、上記の移行が作成されました。しかし、名前を付けたくないので、コードはnullを受け入れる必要があります。そこで、次のような新しい移行を作成しました。

class ChangeNameAndCodeToNotNullInProducts < ActiveRecord::Migration[7.0]
  def change
    change_column :products, :name, :string, null: false
    change_column :products, :code, :string, null: false
  end
end

しかし、製品フォームに移動して「作成」をクリックすると。すべてのデータを空白にして作成することも可能です。私には何が欠けているのでしょうか?

解決策

これは私に一度起こったことです。移行を適用した後、Rails サーバーやコンソールを再起動する必要があります。その後は、not null が尊重されるはずです。