如何修复"参数错误:无法从集合类型推断根键。请指定根或each_serializer选项,或呈现 JSON 字符串'



我正在将一个对象传递给一个返回所有记录的序列化程序,当对象返回空数组时,就会出现此错误。

def booked_cars
if params["id"].present?
@customer = Customer.find(params["id"].to_i)
@booked_cars = @customer.bookings.where(cancelled: false).collect{|c| c.used_car}
render json: @booked_cars, each_serializer: UsedCarSerializer
end
end

我希望它给出对象数组或空数组,而是给出一个参数错误(ArgumentError (无法从集合类型推断根键。请指定根或each_serializer选项,或呈现 JSON 字符串(:)

尝试添加serializer选项或root选项,如active_model_serializer的错误响应中指定的那样。

因为序列化程序从集合中获取根。

@customer = Customer.find(params["id"].to_i)
render json: @customer

在上述情况下,序列化程序将像下面这样响应,

{ 
"customer": #root
{
# attributes ...
}
}

因为对象不是集合,所以根是单数形式(客户(。

@customers = Customer.where(id: ids) # ids is an array of ids.
render json: @customer

在上述情况下,序列化程序将像下面这样响应,

{ 
"customers": #root
{
# attributes ...
}
}

因为对象不是集合,所以根是复数形式(客户(。

序列化程序将根据对象的类添加根(活动记录 ||ActiveRecordCollection(。

如果对象为空,数组序列化程序无法预测将哪个用作根。因此,我们需要指定序列化程序选项。

render json: @customer, root: 'customer'

render json: @customer, serializer: UsedCarSerializer

注意:活动模型序列化程序从对象的类或序列化程序选项中检测序列化程序。

最新更新