问题:render json的格式支持。

class StudentsController < ApplicationController
def show
 @student = Student.find(params[:id])

 render json: @student.to_json(:include => {:courses => {:include => :teacher }})

?不清楚include方法的出处,肯定不是rails api。也不是Ruby里的。

render json: {
 name: @student.name,
 course:
  @student.courses.map { |c|
   {id: c.id, name: c.name, teacher: c.teacher}
  }
}

把对象中的属性提取出来,组成一个key/value对儿。

注意:遍历并返回处理的结果需要使用 Array#map方法

不能使用each, 因为each返回的是对象本身。

> [1, 2].map{|x| x +1}
=> [2, 3]
> [1, 2].each{|x| x +1}
=> [1, 2]

猜你喜欢

转载自www.cnblogs.com/chentianwei/p/9508836.html