在局部视图中传递simple_fields_for对象的Ajax渲染问题咨询
simple_fields_for Builder to Your Partial Got it, let's break this down step by step so you can pass that simple_fields_for builder to your partial in both the initial render and the AJAX re-render. The key here is making sure your partial explicitly accepts the builder object, then passing it correctly from both contexts.
1. Update the Initial Render in abc.html.erb
Right now, your partial isn't receiving the kyc builder from simple_fields_for. You need to pass it as a local variable when rendering the partial:
<%= f.simple_fields_for :kyc_answer do |kyc| %> <div id="id_employer"> <!-- Pass the `kyc` builder to the partial as a local variable --> <%= render 'self_evaluations/self_evaluation_partials/step_2', kyc: kyc %> </div> <% end %>
2. Modify the Partial to Use the Builder
In your step_2 partial, you can now use the kyc builder to generate your form fields. For example, if you need an input for an employer name, you'd write:
<!-- Inside step_2 partial --> <%= kyc.input :employer_name, label: "Employer Name" %> <!-- Add other fields using the `kyc` builder here -->
This ensures your form fields have the correct name attributes (like self_evaluation[kyc_answer][employer_name]) that Rails expects to bind to your model.
3. Fix the AJAX Re-Render in re_render.js.erb
Your current AJAX code passes the @kyc instance variable, but we need to pass a proper simple_fields_for builder instead. First, make sure your controller action sets the parent form object (let's assume it's @self_evaluation, the parent model associated with kyc_answer) before triggering the AJAX render.
Update your re_render.js.erb to create the builder and pass it to the partial:
$('#id_employer').empty() $('#id_employer').append("<%= j simple_fields_for :self_evaluation, @self_evaluation do |f| %> <%= f.simple_fields_for :kyc_answer, @kyc do |kyc| %> <%= render 'self_evaluations/self_evaluation_partials/step_2', kyc: kyc %> <% end %> <% end %>");
Why this works:
- We wrap the partial render in
simple_fields_forfor the parent model (@self_evaluation) to maintain the correct form context. - We then create the
kycbuilder for the:kyc_answerassociation, just like in the initial render, and pass it to the partial. - The
jhelper escapes the HTML so it's safe to inject via JavaScript.
Quick Validation Check
Double-check that your controller action sets both @self_evaluation and @kyc (or ensures @self_evaluation.kyc_answer exists) before rendering the AJAX template. This keeps the form context consistent between initial and AJAX renders.
内容的提问来源于stack exchange,提问作者Kingsley Simon

