Skip to content

Enable config.active_record.belongs_to_required_by_default #1698

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 26, 2025

Conversation

yasulab
Copy link
Member

@yasulab yasulab commented May 26, 2025

以前 Rails 5.0 にアップグレードする過程の残タスクとして、以下の設定のデフォルト値 (true) を上書きしたままになっていたので、本 PR でデフォルト値に戻す PR です。

# TODO: The following config should be switched to its default value `true`, but not urgent.
# Rails 5.0: Require `belongs_to` associations by default. Previous versions had false.
# https://railsguides.jp/configuring.html#config-active-record-belongs-to-required-by-default

- config.active_record.belongs_to_required_by_default = false
+ config.active_record.belongs_to_required_by_default = true

⚠️ 分かりやすさのために上記では false -> true にしてますが、Rails 8.1 などにアップグレードする際に bin/rails app:update を実行すると上記コードは削除される(=デフォルト値に戻る)ので、本 PR では実際には当該コードを削除する形で対応しています ✂️ ✅

やること

  • dba6054 config.active_record.belongs_to_required_by_default をデフォルト値 (true) にする
  • 62d78fc 上記の設定変更後、テストを実行した際に発生した各種エラーを修正する
» AI による修正サポート

#1698 の PR を対応しています。PR 内にある各種リンク先の情報を確認し、テストを実行してください。

bundle exec rspec

PR #1698 の内容に従い、テストを実行しました。

主な失敗内容:

  • 24件のテストが失敗しています。
  • ほとんどの失敗は ActiveRecord::RecordInvalid: バリデーションに失敗しました: Prefectureを入力してください というエラーです。
    • これは belongs_to :prefecture の関連が必須(required)になったため、テストデータ作成時に prefecture が正しく設定されていないことが原因です。

背景:

  • PRの説明通り、config.active_record.belongs_to_required_by_default のデフォルト値(true)に戻したことで、belongs_to 関連が必須になりました。
  • そのため、prefecture_id などの外部キーがnilだとバリデーションエラーになります。

次の対応案:

  • 失敗しているテストのFactoryやテストデータ生成部分で、prefecture または prefecture_id を必ずセットするよう修正する必要があります。

もし該当箇所の修正を進めたい場合は、どのファイルから対応したいかご指示ください。もしくは、失敗しているテストの該当Factoryやspecファイルをリストアップすることも可能です。

@yasulab yasulab added 急ぎじゃないよ Make something better but not rushed. ruby Pull requests that update ruby code labels May 26, 2025
@yasulab yasulab changed the title [WIP] Enable config.active_record.belongs_to_required_by_default Enable config.active_record.belongs_to_required_by_default May 26, 2025
@yasulab yasulab merged commit a6aa9b3 into main May 26, 2025
2 checks passed
@yasulab yasulab deleted the enable-active_record-belongs_to_required_by_default branch May 26, 2025 12:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ruby Pull requests that update ruby code 急ぎじゃないよ Make something better but not rushed.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant