Skip to content

Commit 06d9283

Browse files
authored
Merge pull request #146 from ruby-no-kai/fix-expense-report-data-loss
ExpenseReportsController#create: avoid destroying existing report
2 parents b00e55f + e9ef5df commit 06d9283

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

app/controllers/expense_reports_controller.rb

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ class ExpenseReportsController < ApplicationController
77
before_action :set_expense_report, only: [:show, :update, :calculate]
88

99
def create
10-
begin
11-
@expense_report = current_sponsorship.build_expense_report
12-
@expense_report.save!
13-
rescue ActiveRecord::RecordNotUnique
14-
@expense_report = current_sponsorship.expense_report
10+
@expense_report = current_sponsorship.expense_report
11+
unless @expense_report
12+
begin
13+
@expense_report = ExpenseReport.create!(sponsorship: current_sponsorship)
14+
rescue ActiveRecord::RecordNotUnique
15+
@expense_report = current_sponsorship.reload_expense_report
16+
end
1517
end
1618

1719
respond_to do |format|

spec/requests/expense_reports_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,21 @@
2121
expect(sponsorship.expense_report.status).to eq('draft')
2222
end
2323

24+
context "when expense report already exists with line items" do
25+
let!(:existing_report) { ExpenseReport.create!(sponsorship:) }
26+
let!(:line_item) { FactoryBot.create(:expense_line_item, expense_report: existing_report, position: 1) }
27+
28+
it "preserves the existing report and its line items" do
29+
original_id = existing_report.id
30+
31+
post user_conference_sponsorship_expense_report_path(conference)
32+
33+
expect(response).to redirect_to(user_conference_sponsorship_expense_report_path(conference))
34+
expect(sponsorship.reload.expense_report.id).to eq(original_id)
35+
expect(existing_report.reload.line_items).to eq([line_item])
36+
end
37+
end
38+
2439
it "rejects non-custom sponsorships" do
2540
sponsorship.update_column(:customization, false) # rubocop:disable Rails/SkipsModelValidations
2641
post user_conference_sponsorship_expense_report_path(conference), as: :json

0 commit comments

Comments
 (0)