My nested json payload looks like :
{
"id": 1,
"courses": [
{
"math": [
{
"name": "Math A",
"hours": 10,
"grade": "B"
},
{
"name": "Math B",
"hours": 20,
"grade": "A"
},
{
"name": "Math C",
"hours": 10,
"grade": "B"
}
],
"english": [
{
"number_of_students": 10,
"hours": 20,
"name": "Intro to English",
"grade": "B"
},
{
"number_of_students": 15,
"hours": 25,
"name": "English 101",
"grade": "A"
}
],
},
{}, {}, {}....
]
}
I need to loop through the available options to generate the form, then construct a nested payload as above.
<%= simple_form_for @courses_payload, course_path(id), method: :post do |f| %>
<% available_options.each do |option| %>
<%= f.simple_fields_for Course.new do |c| %>
<%= option.name %>
<% if option.name == "english" %>
<%= c.input : number_of_students %>
<% end %>
<%= c.input :hours %>
<%= c.input :grade %>
<% end %>
<% end %>
<% end %>
api.create(
params[:courses_payload].permit(
courses:[math: [:name, :hours, :grade], english: [:number_of_students, :hours, :name, :grade]]
)
However, I was not able to get all the nested fields into the payload. The form can only record grade field, and not other nested fields(name, hours, number_of_students) . Is there something wrong with my loop?
If I have only hash to work with, I'll use it for my form. But the form applies to models as well, maybe with a few tweaks.
The goal is to make our inputs
name
attributes like this:To make the form submit an actual array is a bit tricky. Input
name
attribute has to look like this:We need to explicitly tell the form builder the index values are blank (nil works in some situations).
A couple of my other answers that involve arrays in forms:
https://stackoverflow.com/a/71688643/207090
https://stackoverflow.com/a/71921385/207090