我有Financing
模型,has_many: :professional_investments
。
要编辑Financing
,主表单包含professional_investments
的嵌套表单。
我决定现在显示一个8 professional_investments
的固定列表,因为Cocoon
gem与Trailblazer的Reform
不匹配。
我使用了两个Reform
表单对象:FinancingForm
和嵌套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
在控制器中,我创建了表单对象,并预先填充它:
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
它有效,但空白ProfessionalInvestment
也会保存在集合中,就像skip_if:
参数无效一样。
如果我未在@financing_form.prepopulate!
中致电update
,则不会按预期保存空白记录。但是,如果存在验证错误,则仅显示现有记录,而不是完整预先填充的8个项目列表。
如何防止保存这些空白记录,同时仍然在update
操作中显示整个预先填充的嵌套列表?