-1

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

Talha Meh
  • 487
  • 7
  • 20
  • You shouldn't ask SO to do your assignments/work for you. You need to show you've at least tried to do this yourself. There's plenty of online tutorials and articles within the reach of Google that can help get you started. Since questions like this are supposed to be down-voted on SO I will do that (sorry), but since you're new around here, I'll also give an answer (without any code) that will point you in the right direction. – Toby 1 Kenobi Sep 03 '17 at 12:04

1 Answers1

0

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.

Toby 1 Kenobi
  • 4,717
  • 2
  • 29
  • 43
  • The question is the relationship between student, batch, and grades. Should I not make Batch a Join Table and then use it as nested_attributes? I'm confused in forming a relationship between student and batch, grades. How'd I fetch Student's grade or fetch grade from batch's grade? – Talha Meh Sep 03 '17 at 14:27
  • No need for a join table. Make each its own model. Student belongs to Grade. Grade has many Students. Grade belongs to Batch. Batch has many Grades. Then you can say `Student.grade.batch` and the other things. – Toby 1 Kenobi Sep 03 '17 at 14:58
  • Also if you put in the Student class `delgate :batch, to: :grade` then you can also say `Student.last.batch` – Toby 1 Kenobi Sep 03 '17 at 15:00
  • I was also thinking to use delegates. Anyhow, thanks! – Talha Meh Sep 03 '17 at 15:16