【问题标题】:How to return a response from rails api with ActiveRecord relations 2 levels deep?如何从具有 ActiveRecord 关系 2 级深的 rails api 返回响应?
【发布时间】:2021-09-30 04:48:25
【问题描述】:

我正在为教师创建一个 Rails api,以根据某些标准对学生进行排名。我有四种模型:课堂、学生、标准和排名。

  • 通过排名,学生/标准是多对多的
  • 学生/教室多对多
  • Rank 是 Student/Criteria 与附加字段 rank 之间的连接表,该字段是 1-4 之间的整数。

通过允许 Classroom.students 在我的课堂序列化程序中通过,我能够在响应中返回属于课堂的学生列表(1 个关系深度)。如何从我的 API 返回每个学生在我的课堂响应(2 个关系深度)中嵌套在学生中的排名?理想的反应如下:

教室_A:

{
  id: "123",
  name: "classroom A",
  students: [
    { id: "456"
      name: Juanita,
      gender: female,
      ranks: [
        { id: "789",
          student_id: "456",
          name: "willingness to help others",
          rank: "4"
         },
         { id: "101",
          student_id: "456",
          name: "Leadership",
          rank: "3"
         } ...
       ]
    },
    { id: "232"
      name: Billy,
      gender: male,
      ranks: [
        { id: "789",
          student_id: "232",
          name: "willingness to help others",
          rank: "3"
         },
         { id: "101",
          student_id: "232",
          name: "Leadership",
          rank: "3"
         } ...
       ]
    }
  ]
}

提前致谢。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord ruby-on-rails-5


【解决方案1】:

Rails: Serializing deeply nested associations with active_model_serializers 发布了类似的问题(感谢@lam Phan 的链接)

但是,该帖子获得最多支持的答案不是很清楚,也没有代码示例。超级失望。我还查看了 JsonApi 适配器,但无法获得我正在寻找的解决方案。最后,对于链接问题,我最终采取了与 OP 相同的路线:在序列化程序中,我编写了自己的函数并手动加载了我想要的其他数据。我希望以“Rails 方式”来做这件事,但最后我选择了完成它。

class ClassroomSerializer < ApplicationSerializer
  attributes :id, :name, :school_name, :students

  def students
    customized_students = []

    object.students.each do |student|
      custom_student = student.attributes
      custom_student['ranks'] = student.student_ranks
      customized_students.push(custom_student)
    end
    customized_students
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多