我将一个对象传递给一个序列化程序,该序列化程序返回所有记录,当对象返回空数组时,这个错误就会出现。
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字符串):)
发布于 2019-08-09 02:22:36
尝试添加来自serializer
的错误响应中指定的root
选项或active_model_serializer选项。
因为序列化程序从集合中获取根。
@customer = Customer.find(params["id"].to_i)
render json: @customer
在上述情况下,序列化程序将响应如下,
{
"customer": #root
{
# attributes ...
}
}
因为对象不是集合,所以根目录是单数form(customer).。
@customers = Customer.where(id: ids) # ids is an array of ids.
render json: @customer
在上述情况下,序列化程序将响应如下,
{
"customers": #root
{
# attributes ...
}
}
因为对象不是集合,所以根目录是复数form(customers).。
序列化程序将根据对象的类添加根目录(ActiveRecord财政/ ActiveRecordCollection)。
如果对象是空数组,则序列化程序无法预测使用哪一个作为根。因此,我们需要指定根或序列化程序选项。
render json: @customer, root: 'customer'
或
render json: @customer, serializer: UsedCarSerializer
注意:活动模型序列化程序从对象的类或序列化器选项中检测序列化程序。
https://stackoverflow.com/questions/57427120
复制