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

后端 未结 2 885
囚心锁ツ
囚心锁ツ 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:33

    Use JBuilder, it comes by default with Rails. Ignore the lines starting with '#':

    Jbuilder.new do |j|
    
        # courses: [{
        j.courses  do |course|
    
          # id: 
          j.id course.id 
    
          # name: 
          j.name course.name
    
          # students: [{
          j.students  do |student|
    
              # name: 
              j.name student.name
    
          end
          # }]
    
       end
       # }]
    
    end
    

    Not a lot of code. Removing the comments and simplifying some features, it will look like:

    student_courses = <...blah...>
    json = Jbuilder.new do |j|
      j.courses student_courses do |course|
        j.(course, :id, :name)
        j.students , :name
      end
    end.target!
    

    Check out their guide, its pretty awesome to generate JSON in plain Ruby DSL. So go ahead and use whatever ruby code you want to fetch students/courses/studentcourses.

提交回复
热议问题