简体   繁体   English

使用ActiveModel :: Serializer时如何隐藏created_at和updated_at

[英]How to hide created_at and updated_at when using ActiveModel::Serializer

I'm using active_model_serializers in rails application it's working perfectly fine, but when dealing with associations it's returning all the attributes of the associated model (including the created_at and updated_at) which I don't want to be returned. 我在rails应用程序中使用active_model_serializers可以正常工作,但是在处理关联时,它将返回我不想返回的关联模型的所有属性(包括created_at和updated_at)。

class ReservationSerializer < ActiveModel::Serializer
 attributes :id, :pnr_no, :train_no, :passenger_name, :from_to, 
 :travel_class, :cancelled, :travel_time
 has_many :reservation_seats
end

 ...
 attributes of reservation are returned, which are fine therefore only 
 including the relationship attributes i.e for reservation_seats
...

"relationships": {
    "reservation-seats": {
      "data": [
        {
          "id": 4,
          "reservation-id": 5,
          "seat-no": "26",
          "position" : "2",
          "created-at": "2017-05-27T23:59:56.000+05:30",
          "updated-at": "2017-05-27T23:59:56.000+05:30"
        }
      ]
    }

I tried creating a new file as well, where I have defined the attributes which needed to returned, but in this case it's just returning type only. 我也尝试创建一个新文件,在其中定义了需要返回的属性,但是在这种情况下,它只是返回类型。

class ReservationSeatSerializer < ActiveModel::Serializer
  attributes :id, :seat_no, :position
  belongs_to :reservation
end

this is resulting in: 这导致:

"relationships": {
    "reservation-seats": {
      "data": [
        {
          "id": "4",
          "type": "reservation-seats"
        }
      ]
    }
  }

Basically for the association I only want few attributes to be returned. 基本上,对于关联,我只希望返回几个属性。

Thanks 谢谢

The JSON API spec wants you to reduce the response data and database requests by just including the type and identifier of the relation. JSON API规范希望您仅通过添加关系的类型和标识符来减少响应数据和数据库请求。 If you want to include the related object, you have to include it: 如果要包含相关对象,则必须包含它:

ActiveModelSerializer Example: ActiveModelSerializer示例:

render json: @reservation, include: '*'

This includes all the relationships recursively. 这包括所有关系的递归。 These related objects will end up in the included array. 这些相关对象将最终出现在included数组中。

Take a look at the JSON API spec and the active_model_serializer docs . 看一下JSON API规范active_model_serializer文档

You could try adding a serializer of your association inside of it: 您可以尝试在其中添加关联的序列化器:

class ReservationSerializer < ActiveModel::Serializer
  attributes :id, :pnr_no, :train_no, :passenger_name, :from_to, 
  :travel_class, :cancelled, :travel_time
  has_many :reservation_seats

  class ReservationSeatSerializer < ActiveModel::Serializer
    attributes :id, :seat_no, :position
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM