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

标签 ruby-on-rails active-model-serializers

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

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/

相关文章:

ruby-on-rails - 不指向 rails 和 postgres 中的主键的外键?

ruby-on-rails - gmail 阻止 Rails 应用程序发送电子邮件

ruby-on-rails - 如何不对应用程序中的特定页面使用 application.html.erb 文件?

ruby-on-rails - Ember-Data beta 3 并保存 hasMany 关系以及与 Rails 的另外一条记录

ruby-on-rails - 如何将响应格式从 fast_jsonapi 格式更改为 AMS gem 响应格式

ruby-on-rails - Rails ActiveModel 序列化程序 : Retrieving Deeply Nested ActiveRecord Association

ruby-on-rails - Ruby 2.4 和 BigDecimal 错误(无效值)

ruby-on-rails - : rails vs. bin/rails 有什么区别?

ruby-on-rails - ActiveModel::Serializer 可以像 Rails Controller 那样具有命名空间名称(嵌套)吗?

ruby-on-rails - 在 rails api 事件模型序列化程序中为关联属性使用不同的键名