我正在使用:
- active_model_serializers 0.10.8
- 红宝石2.5.3p105
- 轨道5.2.1.1
序列化程序:
class CarSerializer < ActiveModel::Serializer
attributes :make, :model
end
如果我这样做:
class MyController < ApplicationController
def index
@cars = Car.all
render json: @cars
end
end
然后我的API按预期返回,只返回make和model属性(而不是ID或时间戳(。一切都很好。
如果我将控制器更改为:
@cars = Car.all
render json: {
cars: @cars
}
它不再使用序列化程序,而是返回完整的模型(id、make、model、时间戳(。
我正在尝试这样做,因为我想返回多个模型,即:
render json: {
cars: @cars,
drivers: @drivers
}
我哪里错了?当我把它添加到哈希中时,为什么它不序列化?
ruby和rails的新手,为任何愚蠢的错误道歉!
谢谢!
计算出来,应该是:
render json: {
cars: ActiveModelSerializers::SerializableResource.new(Car.all),
drivers: ActiveModelSerializers::SerializableResource.new(Driver.all)
}