I have two tables Student and Teacher let’s suppose for the sake of example. There is a third table, the joining table which has student_id and teacher_id with additional attribute say subject.
I now want to attribute many Students to one Teacher or one Teacher to many Students, where Students records already exist and I want one or more students to be attributed to one Teacher with the subject value for each of them. What would be the best way to do this ? I’m not 100% confident if the schema design is also correct, but the use case is absolute reflection of what I’m trying to do.
I tried using put_assoc
for the building association against student, and cast_assoc
for the teacher value, and my changeset definition for the joining table looks like this -
def changeset(model, params) do
model
|> cast(params, @required)
|> validate_required(@required)
|> cast_assoc(:teacher)
|> put_assoc(:student, params.student)
end
This works for while inserting one student, but when inserting next record the Teacher would exist already and there is a chance it will insert multiple records for the same Teacher.
Also is it possible to get the below two responses for these both models ?
// for Student
{
"student": {
"name": "Mojo Jojo",
"teachers": [{
"name": "Prof. Utonium",
"subject": "Chemistry"
}]
}
}
// for Teacher
{
"teacher": {
"name": "Prof. Utonium",
"students": [{
"name": "Mojo Jojo",
"subject": "Chemistry"
}]
}
}