-
Notifications
You must be signed in to change notification settings - Fork 0
Problem with nesting forms
This issue has been identified during an upgrade from Rails 4.2.9 to Rails 5.0.6.
Scenario A form is added to a view to allow the details of an object to be updated.
The form is composed of multiple sections, each set of fields are extracted into a partial. Not all of the sections have data that is stored on the object. One such section contains a form_tag used to add data, via ajax requests to the server, for another object associated with the form's object.
Problem The issue manifests when the submit button is clicked, as the data is submitted to the parent form path and raises an exception.
Troubleshooting When viewing the DOM elements via DevTools in the browser, only the nested fields and submit button are add to the * DOM, the form element is omitted.
- When viewing the page source the parent form, nested form, and it's fields are included.
- The problem may be intermittent, i.e. when switching be admin and user roles where permissions control which fields the user may access.
Suggested Solution Reconsider the layout of the view. Does the nested form really need to exist within the parent form? In this case the nested field logic was already extracted into a partial and based on the user's permissions either the partial or the form could be displayed.
<!-- parent form for saving user data -->
<%= form_for(@user, url: user_admin_path(@user), method: :put, html: { multipart: true, class: nil }) do |f| %>
<!-- nested form for saving -->
<%= form_tag(user_mentor_relationships_path(@user), method: :post) do %>
<div class="form-group">
<%= select_tag :user_mentors, [],
multiple: true,
placeholder: 'E.g. dixona',
class: 'form-control input-sm js-mentor-select',
data: {
options: mentors_data(@user.mentors),
mentors_path: mentors_path(@user.id)
}
%>
</div>
<div class="col-xs-12 col-sm-12 col-md-2 pull-right">
<%= submit_tag 'Save Mentors', class: 'btn btn-primary btn-block' %>
</div>
<% end %>
<% end %>