如何从rails api返回activerecord关系为2级的响应?

6ss1mwsb  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(301)

我正在为教师创建一个rails api,以便根据某些标准对学生进行排名。我有四个模型:教室、学生、标准和等级。
学生/标准是通过等级的多对多
学生/教室是多对多的
rank是学生/标准与rank附加字段之间的联接表,rank是1-4之间的整数。
我可以通过允许Classification.students通过我的课堂序列化程序返回属于某个课堂的学生列表作为响应(1关系深度)。如何从api返回课堂React(2个关系深度)中嵌套在学生中的每个学生的排名?理想的回答如下:
教室a:

  1. {
  2. id: "123",
  3. name: "classroom A",
  4. students: [
  5. { id: "456"
  6. name: Juanita,
  7. gender: female,
  8. ranks: [
  9. { id: "789",
  10. student_id: "456",
  11. name: "willingness to help others",
  12. rank: "4"
  13. },
  14. { id: "101",
  15. student_id: "456",
  16. name: "Leadership",
  17. rank: "3"
  18. } ...
  19. ]
  20. },
  21. { id: "232"
  22. name: Billy,
  23. gender: male,
  24. ranks: [
  25. { id: "789",
  26. student_id: "232",
  27. name: "willingness to help others",
  28. rank: "3"
  29. },
  30. { id: "101",
  31. student_id: "232",
  32. name: "Leadership",
  33. rank: "3"
  34. } ...
  35. ]
  36. }
  37. ]
  38. }

提前谢谢。

dba5bblo

dba5bblo1#

rails上发布了一个类似的问题:使用活动的_model_序列化程序序列化深度嵌套的关联(感谢链接@lam phan)
然而,这篇文章中投票最多的答案并不十分清楚,也没有代码示例。超级失望。我还研究了jsonapi适配器,但没有找到我想要的解决方案。最后,对于链接的问题,我采用了与op相同的方法:在序列化程序中,我编写了自己的函数,并手动侧载了所需的其他数据。我本希望用“rails方式”来完成这项工作,但最终我选择了直接完成。

  1. class ClassroomSerializer < ApplicationSerializer
  2. attributes :id, :name, :school_name, :students
  3. def students
  4. customized_students = []
  5. object.students.each do |student|
  6. custom_student = student.attributes
  7. custom_student['ranks'] = student.student_ranks
  8. customized_students.push(custom_student)
  9. end
  10. customized_students
  11. end
  12. end
展开查看全部

相关问题