Rebuild the account from the submission when a create fails late

Merged
JA
1mo ago
+43-3

Split out of #3474, where it was out of scope (jjmata's review, CodeRabbit's out-of-scope check). One commit on current main.

Problem

AccountableResource#create saves with save!, and a validation can be tripped after the account itself is valid: the opening valuation's entries.create!, or lock_saved_attributes!. The record on that RecordInvalid is an Entry or the accountable, not the account the form renders. The rescue handled that by building a blank account, so the user got an empty form back with everything they had typed gone. When the account itself is what fails, the form already comes back filled in; this is the one path where it did not.

Change

In the rescue, when the exception's record is neither an account nor something that leads to one, rebuild the account from account_params (minus return_to and opening_balance_date, which are not attributes) instead of a fresh Account. Account#accountable_type= builds the nested accountable during mass assignment, so the rebuilt account renders in the form as the submitted one would have.

Nothing else changes: the transaction has already rolled back before the rescue, the 422 status and error message are as before, and the first two branches of the rescue are untouched.

Validation

  • test/controllers/loans_controller_test.rb, "a create that fails on the opening valuation still re-renders the form", now also asserts that account[name] and the nested loan interest_rate come back. With main's rescue it fails (found 0 for the name input); with this change it passes.
  • Loans and accounts controller suites: 100 runs, 0 failures. bin/rubocop on both files clean.

Run locally on Ruby 3.3.6 with the version pin overridden; CI runs on 3.4.9.

Rebased onto main (6 Oct)

Rebased onto main at eb34c06f0; the commits carry the same changes under new SHAs, apart from the conflict resolutions below. SHAs elsewhere in this description refer to the commits as they were before.

  • e955062ea → ae8787430 Rebuild the account from the submission when a create fails late
  • 771eae605 → 55f14e0c2 Build the nested accountable when the submission named none

Conflicts: test/controllers/loans_controller_test.rb: #3474 brought this test in with its last two assertions split out to this PR; they are kept.

bin/rails test on 55f14e0c2: 10,566 runs, 44,986 assertions, 0 failures, 0 errors, 33 skips. bin/rubocop on the changed files: no offenses.

Summary by CodeRabbit

  • Bug Fixes
    • When loan creation fails validation, the form now retains the submitted account name instead of displaying a blank account.
    • If nested loan details are missing, the new-loan form still renders with the interest-rate field. The form also preserves the submitted account information, so you can review the details and correct the submission without starting over.