Rails 5からbelongs_to associationを書くと親はデフォルト必須になった

はじめに

Rails 5(Rails 5.1?)からbelongs_to associationを書くと親が必須になっていました。これに今日はドハマリした...

具体的には、

class Post < ApplicationRecord
  belongs_to :article
end

というmodelがあったとして、rails consoleなどでPostインスタンスsaveしようとするとvalidationエラーが出ます。

> Post.new.save!
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
Traceback (most recent call last):
        1: from (irb):3
ActiveRecord::RecordInvalid (Validation failed: Article must exist)
>

経緯

Rails 5.0から5.1にアプリをあげてテストを流していたときに大量にテストが落ちたことがきっかけです。解決に至ったのは、次のブログ。

48n.jp

回避

上記のブログにあるように、belongs_tooptional: trueをつければOKです。ソース全体を書くと

class Post < ApplicationRecord
  belongs_to :article, optional: true
end

と言った感じになります。

実際にrails consoleで確かめてみます。

> Post.new.save!
   (0.1ms)  begin transaction
  Post Create (0.5ms)  INSERT INTO "posts" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2018-09-25 11:29:33.968321"], ["updated_at", "2018-09-25 11:29:33.968321"]]
   (1.3ms)  commit transaction
=> true
>

無事、生成できました。