A student gets admitted to a school and in its admission form, I want the user to assign student his/her batch and grade as well. Batch has many grades and grade belongs to batch.
In this scenario, I've to create a student form where I need the user to select pre-created batch and grade for the student. How should I create a fields_for form to select batch and grade for the student?
The Requirement is, there should be a dropdown where the user can select a batch and then the selected batch's grade and assign it to the student after submitting the form. So the student can have his/her batch and grade. So i could achieve something like:
Grade.last.students
,
Student.last.grade.batch
,
Student.last.grade
Since the batches and grades are pre-created I wouldn't use the nested attributes feature of Rails for this.
The simplest way to do this is to have in the admission form a dropdown that displays all the batches, and also, for each batch have a hidden dropdown for all the grades in that batch (so if there are 10 batches you have one batch dropdown and 10 separate hidden dropdowns for grades) then use JS to show the relevant grades dropdown when that particular batch is selected.
The dropdowns will use the ids for the batches/grades as its values, then the controller can find these in the database and assign them to the student.
If the number of batches is pretty big, and this becomes unwieldy, then I would use AJAX to populate the grades dropdown box whenever the selected batch changes.