繁体   English   中英

在Ruby on Rails中格式化JSON响应

[英]Formating json response in Ruby on Rails

我有一个带有学生ID,名称和课程ID的学生表。 我需要获取表中的所有记录作为Ruby on Rails中的 json响应。 我需要格式的json

 {"records" : [{ "course" : 1  #course id in the table
    "students" : [ {
           "id" : 5
           "name" : "Ragav"
           },
           {
            "id":6,
            "name": "Rohith"
           }]
   },
   { "course":2,
     "students" : [ {
           "id" : 8
           "name" : "Ragav"
           },
           {
            "id":10,
            "name": "Rohith"
           }]
      }
 ]}

我正在像这样使用JBuilder进行此操作

json = Jbuilder.new do |j|
  j.id student_id
  j.name name
end

在模型的as_json方法中。 我是RoR的新手。 请帮忙

由于您正在使用JBuilder,因此您实际上应该利用模板来呈现JSON。 这样做可以将视图和模型层分开,并允许您缓存和重用模板部分。

这是一个基本示例:

假设这是对CoursesController上的index操作的响应,则将@courses作为实例变量传递给视图

# Controller, responding to json requests
class CoursesContrller < ApplicationController

   respond_to :json

   def index
      @courses = Courses.all
   end
end

默认情况下,它将在/views/courses/index.json.jbuilder寻找相应的模板

您可以使用JBuilder模板定义JSON结构:

json.records do
  json.array! @courses do |course|
    json.course course.id
    json.students do
      json.array! course.students do |student|
        json.id   student.id
        json.name student.name
      end
    end
  end
end
@students = Student.all
@studnetlist = @students.map do |u|
  { :id => u.id, :name => u.name }
end
json = @studnetlist.to_json

你可以这样做。 根据需要修改json。

在您的模型中尝试一下

 students_data = Student.select(:id,:name,:course_id).group_by(&:course_id).collect{|k, v| {course: k, students: v}}.as_json

{ records: students_data }

您需要在views文件夹中创建.jbuilder文件。 例如:

app / views / students / show.json.jbuilder

json.extract! @student, :student_id, :course, :course_id

当然,还可以在控制器方法中呈现json。

您可以在此处找到有用的示例。 希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM