I have a model Financingwith has_many: :professional_investments.
To edit Financing, the main form has a nested form for professional_investments.
I decided to display a fixed list of 8 professional_investments, since the gem Cocoondoes not work very well with Trailblazer Reform.
I use two form objects Reform: a FinancingFormand 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 a 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 empty ones are ProfessionalInvestmentalso stored in the collection, as if the parameter skip_if:had no effect.
@financing_form.prepopulate! update, , . , , , 8 .
update?