0

I am have student table with fields student_id, name and course_id. I need to fetch all records in the table as json response in Ruby on Rails. I need the json in the format

 {"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

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

in as_json method in model. I am new in RoR. Please help

4 Answers 4

2

Since you're using JBuilder you should really be making uses of templates to render your 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

# 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

You can define your JSON structure using a JBuilder template:

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
Sign up to request clarification or add additional context in comments.

Comments

0
@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.

Comments

0

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 }

Comments

0

you need to create .jbuilder file in your views folder. For example:

app/views/students/show.json.jbuilder

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

And of course render json in your controller method.

You can find useful examples here. Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.