我的学生表包含字段student_id,name和course_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的新手。请帮忙
答案 0 :(得分:2)
由于你正在使用JBuilder,你应该真正使用模板来呈现你的JSON。这样做可以使视图和模型层分开,并允许您缓存和重用模板部分。
这是一个基本的例子:
假设这是对index
上的CoursesController
操作的响应,您将@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
答案 1 :(得分:0)
@students = Student.all
@studnetlist = @students.map do |u|
{ :id => u.id, :name => u.name }
end
json = @studnetlist.to_json
你可以这样做。根据您的需要修改json。
答案 2 :(得分: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 }
答案 3 :(得分:0)
您需要在 views 文件夹中创建 .jbuilder 文件。 例如:
应用/视图/生/ show.json.jbuilder 强>
json.extract! @student, :student_id, :course, :course_id
当然,在你的控制器方法中渲染json。
您可以找到有用的示例here。希望它有所帮助。