In a Rails ( 4.1.5 / ruby 2.0.0p481 / win64 ) application I have a many-to-many relationship between Student and Course and a join model StudentCourse
Use JBuilder, it comes by default with Rails. Ignore the lines starting with '#':
Jbuilder.new do |j|
# courses: [{
j.courses do |course|
# id:
j.id course.id
# name:
j.name course.name
# students: [{
j.students do |student|
# name:
j.name student.name
end
# }]
end
# }]
end
Not a lot of code. Removing the comments and simplifying some features, it will look like:
student_courses = <...blah...>
json = Jbuilder.new do |j|
j.courses student_courses do |course|
j.(course, :id, :name)
j.students , :name
end
end.target!
Check out their guide, its pretty awesome to generate JSON in plain Ruby DSL. So go ahead and use whatever ruby code you want to fetch students/courses/studentcourses.