簡體   English   中英

使用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規范active_model_serializer文檔

您可以嘗試在其中添加關聯的序列化器:

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