gpt4 book ai didi

ruby-on-rails - 如何修复 'ArgumentError: Cannot infer root key from collection type. Please specify the root or each_serializer option, or render a JSON String'

转载 作者:行者123 更新时间:2023-12-04 13:18:27 25 4
gpt4 key购买 nike

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

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(无法从集合类型推断根键。请指定根或每个_serializer 选项,或呈现 JSON 字符串):)

最佳答案

尝试按照 active_model_serializer 的错误响应中的指定添加 serializer 选项或 root 选项。

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

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

在上面的例子中,序列化器会像下面这样响应,

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

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

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

在上面的例子中,序列化器会像下面这样响应,

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

因为对象不是集合,所以词根是复数形式(customers)。

序列化器会根据对象的类(ActiveRecord || ActiveRecordCollection)添加root。

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

render json: @customer, root: 'customer'

 render json: @customer, serializer: UsedCarSerializer

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

关于ruby-on-rails - 如何修复 'ArgumentError: Cannot infer root key from collection type. Please specify the root or each_serializer option, or render a JSON String',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57427120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com