简体   繁体   English

在Ruby on Rails中格式化JSON响应

[英]Formating json response in Ruby on Rails

I am have student table with fields student_id, name and course_id. 我有一个带有学生ID,名称和课程ID的学生表。 I need to fetch all records in the table as json response in Ruby on Rails . 我需要获取表中的所有记录作为Ruby on Rails中的 json响应。 I need the json in the format 我需要格式的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"
           }]
      }
 ]}

I am doing this using JBuilder like this 我正在像这样使用JBuilder进行此操作

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

in as_json method in model. 在模型的as_json方法中。 I am new in RoR. 我是RoR的新手。 Please help 请帮忙

Since you're using JBuilder you should really be making uses of templates to render your JSON. 由于您正在使用JBuilder,因此您实际上应该利用模板来呈现JSON。 Doing so keep your view and model layer separate, and allow you to cache and reuse template partials. 这样做可以将视图和模型层分开,并允许您缓存和重用模板部分。

Here's a basic example: 这是一个基本示例:

Assuming this is the response to the index action on CoursesController you pass the @courses as an instance variable to the view 假设这是对CoursesController上的index操作的响应,则将@courses作为实例变量传递给视图

# Controller, responding to json requests
class CoursesContrller < ApplicationController

   respond_to :json

   def index
      @courses = Courses.all
   end
end

By default, this will look for a corresponding template at /views/courses/index.json.jbuilder 默认情况下,它将在/views/courses/index.json.jbuilder寻找相应的模板

You can define your JSON structure using a JBuilder template: 您可以使用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

You can do this. 你可以这样做。 Modify json according to your need. 根据需要修改json。

try this out in your model 在您的模型中尝试一下

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

{ records: students_data }

you need to create .jbuilder file in your views folder. 您需要在views文件夹中创建.jbuilder文件。 For example: 例如:

app/views/students/show.json.jbuilder app / views / students / show.json.jbuilder

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

And of course render json in your controller method. 当然,还可以在控制器方法中呈现json。

You can find useful examples here . 您可以在此处找到有用的示例。 Hope it helps. 希望能帮助到你。

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

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