I have a Financing
model with has_many: :professional_investments
.
To edit the Financing
, the main form has a nested form for the professional_investments
.
I decided to display a fixed list of 8 professional_investments
for now, as the Cocoon
gem does not play well with Trailblazer's Reform
.
I use two Reform
form objects: a FinancingForm
, and a nested ProfessionalInvestmentForm
:
class FinancingForm < Reform::Form
collection :professional_investments,
form: ProfessionalInvestmentForm,
prepopulator: :prepopulate_professional_investments,
populate_if_empty: :populate_professional_investments!,
skip_if: :professional_investment_blank?
def prepopulate_professional_investments(options)
[8 - professional_investments.size, 0].max.times do
professional_investments << ProfessionalInvestment.new
end
end
def populate_professional_investments!(fragment:, **)
ProfessionalInvestment.new unless professional_investment_blank?(fragment: fragment)
end
def professional_investment_blank?(fragment:, **)
fragment['professional_investor_id'].blank? && fragment['amount'].to_d.zero?
end
end
In the controller, I create the form object, and pre-populate it:
class FinancingsController < ApplicationController
def edit
@financing_form = FinancingForm.new(@financing)
@financing_form.prepopulate!
end
def update
@financing_form = FinancingForm.new(@financing)
@financing_form.prepopulate!
if @financing_form.validate(financing_params)
@financing_form.save
end
end
end
It works, except that blank ProfessionalInvestment
are saved as well in the collection, as if the skip_if:
parameter had no effect.
If I don't call @financing_form.prepopulate!
in update
, the blank records are not saved, as intended. But then, if there are validation errors, only the existing records are displayed, not the full pre-populated 8 items list.
How to prevent these blank records from being saved, while still displaying the whole pre-populated nested list in the update
action?