Rendering a JSON object of a join-model and its associated models

后端 未结 2 798
囚心锁ツ
囚心锁ツ 2021-02-06 03:09

In a Rails ( 4.1.5 / ruby 2.0.0p481 / win64 ) application I have a many-to-many relationship between Student and Course and a join model StudentCourse

2条回答
  •  庸人自扰
    2021-02-06 03:39

    Use scope to your advantage:

    class Course < ActiveRecord::Base
      # ...
      scope :not_started, -> { joins(:student_courses) \
                                          .where(student_courses: {started: false}) }
    
      scope :with_classmates, -> { includes(:students) } # use eager loading
    end
    

    Then call:

    @student.courses.not_started.with_classmates \
                                         .to_json(include: {students: {only: :name}})
    

    Output:

    [
        {
            "id": 1,
            "name": "english",
            "description": null,
            "students": [
                {"name": "Aiden"},
                {"name": "Alison"}]},
        {
            "id": 2,
            "name": "music",
            "description": null,
            "students": [
                {"name": "Aiden"},
                {"name": "Alison"}]},
        {
            "id": 3,
            "name": "dance",
            "description": null,
            "students": [
                {"name": "Aiden"}]}]
    

提交回复
热议问题