Ruby on Rails 外部キー制約カラムにNULL値を許可する方法
Ruby on Railsにおいて、カラムに外部キーを設定するとNULL値を登録することができない。外部キー制約を設定しつつ、NULL値を許可する方法を下記に示す。
現状
下記の場合、外部キー制約が設定されたカラムにNULL値は登録できない。
productテーブルのマイグレーションファイル
カラム:product_brandを外部キーとして設定
null :false の設定はしていない
def change
create_table :products do |t|
t.references :product_brand, foreign_key: true
t.timestamps
end
end
end
product モデル
class Product < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :product_brand
end
上記状態の場合、productテーブルのカラムproduct_brandはNULL値を登録することができない。
修正
下記のようにoptional: trueを設定することでNULL値が登録できるようになる。
peoductモデル
optional: true を設定するとproductテーブルのカラムproduct_brandにNULL値を登録することが可能となる。
class Product < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :product_brand, optional: true
end