0

我在用:

  • 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 按预期返回,只是品牌和型号属性(不是 ID 或时间戳)。都好。

如果我将控制器更改为:

@cars = Car.all

render json: {
  cars: @cars
}

它不再使用序列化程序并返回完整的模型(id、make、model、时间戳)。

我正在尝试这样做,因为我想返回多个模型,即:

render json: {
  cars: @cars,
  drivers: @drivers
}

我哪里错了?为什么当我将它添加到哈希时它不序列化?

ruby 和 rails 的新手,为任何愚蠢的错误道歉!

谢谢!

4

1 回答 1

0

算了,应该是这样的:

render json: {
      cars: ActiveModelSerializers::SerializableResource.new(Car.all),
      drivers: ActiveModelSerializers::SerializableResource.new(Driver.all)
}
于 2018-12-13T13:22:31.537 回答