简体   繁体   中英

Rails 5.0 - How to dynamically render a nested form?

I have expenses which have multiple expense_types , and each expense_type has a form with multiple, specific fields.

Upon creating an expense , I can select which expense_type it will have, and through AJAX I'd like to render the fields_for the selected expense_type .

For example, let's say an expense has a person's name and expense_cost : upon selecting the expense_type travel , it also includes the fields itinerary and start_date / end_date on the page.

I have the following lines of code to render any of the selected expense_types , within the expense form:

<% if @expense_type.present? %>
  <%= f.fields_for ("expense_#{@expense_type}").to_sym do |ff| %>
    <%= render "expense_#{@expense_type.pluralize}/#{@expense_type}_form", f: ff %>
  <% end %>
<% end %>

If I call an action to set @expense_type = params[:selected_expense_type] , and then tell it to render :new , it'll display the selected form as intended, but I'll lose the data the user had already supplied.

How can I set this variable without losing the expense 's current form data? Is there perhaps a better way to do this?

Thanks!

The solution was to send the current form's content through AJAX and set the expense object with it, then I added this to my ApplicationHelper :

def render_if_exists(path, *args)
  render path, *args
rescue ActionView::MissingTemplate
  nil
end

and updated my renderer with it:

<% if @expense_type.present? %>
  <%= f.fields_for ("expense_#{@expense_type}").to_sym do |ff| %>
    <%= render_if_exists "expense_#{@expense_type.pluralize}/#{@expense_type}_form", f: ff %>
  <% end %>
<% end %>

With this, I'm able to load the expense 's form alone, then upon selecting an expense_type from the dropdown, it would send a request back to expenses/new with the current form's content and set the @expense object with the old values, as well as looking for a partial which would match my convention ( expense_expense_types/expense_type_form ), and rendering it if it found one for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM