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

How to hide created_at and updated_at when using ActiveModel::Serializer

我在 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"
        }
      ]
    }

我也尝试创建一个新文件,我在其中定义了需要返回的属性,但在这种情况下它只是返回类型。

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

这导致:

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

基本上对于关联,我只希望返回几个属性。

谢谢

JSON API 规范希望您通过仅包含关系的类型和标识符来减少响应数据和数据库请求。如果要包含相关对象,则必须包含它:

ActiveModelSerializer 示例:

render json: @reservation, include: '*'

这包括递归的所有关系。这些相关对象将最终出现在 included 数组中。

看看JSON API spec and the active_model_serializer docs

您可以尝试在其中添加关联的序列化程序:

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