2017-01-17 48 views
0

我有student_id,name和course_id字段的學生表。我需要獲取表格中的所有記錄作爲json響應Ruby on Rails。我需要的JSON格式在Ruby on Rails中格式化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" 
      }] 
     } 
]} 

我在as_json方法模型做這個用的JBuilder這樣

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

。我是RoR的新手。請幫忙

回答

2

由於您使用JBuilder,您應該真正使用模板來呈現您的JSON。這樣做可以保持視圖和模型層分離,並允許您緩存和重用模板部分。

這裏有一個基本的例子:

假設這是你通過@courses作爲一個實例變量視圖

# Controller, responding to json requests 
class CoursesContrller < ApplicationController 

    respond_to :json 

    def index 
     @courses = Courses.all 
    end 
end 

默認情況下,這將尋找到index動作的響應上CoursesController相應的模板在/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 
0
@students = Student.all 
@studnetlist = @students.map do |u| 
    { :id => u.id, :name => u.name } 
end 
json = @studnetlist.to_json 

你可以這樣做。根據您的需要修改json。

0

試試這個模型中的

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

{ records: students_data } 
0

你需要在你意見文件夾中創建.jbuilder文件。 例如:

應用程序/視圖/學生/ show.json.jbuilder

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

當然,在你的控制器方法渲染JSON。

你可以找到有用的例子here。希望能幫助到你。