Multiple classes for one student

Asked

Viewed 41 times

0

I have a teaching application in it I have a model for Classes (Room) and another for Students (Student).

In my business rule, each student can be enrolled in up to three classes. For this I simply created 3 more columns in the student register.

  1. room_1 (integer)
  2. room_2 (integer)
  3. room_3 (integer)

And in the creation I place the class id manually (form select) inside each column.

My problem is that:

  1. I know it’s not the right way to create this relationship.
  2. I’m having several problems at the time of generating report why I need to take several turns to consult the data.

1 answer

1

First it is necessary to make a table N:N.

rails g model student_rooms student:references room:references

Now, we do the migrations to create the foreign_keys.

rails g migration AddStudentRoomToRooms student_room:references
rails g migration AddStudentRoomToStudents student_room:references
rails db:migrate

In the models:

class StudentRoom
 belongs_to :student
 belongs_to :room
...

class Room
 has_many :student_rooms
 has_many :students, through: :student_rooms 
...

class Student
  has_many :student_rooms, validates_length_of :rooms, maximum: 3
  has_many :rooms, through: :student_rooms
...

One Room has many students and a Student has many rooms. A table StudentRooms serves only to connect the two Tables. What prevents a Student has more than 3 Rooms is the validates_length_of.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.