0

我在rails應用程序中使用active_model_serializers它工作得很好,但是在處理關聯時,它將返回關聯模型的所有屬性(包括created_at和updated_at)我不想被退回。如何在使用ActiveModel :: Serializer時隱藏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" 
     } 
     ] 
    } 
    } 

基本上爲聯想,我只想要返回幾個屬性。

感謝

+1

這將是更容易回答這個問題更多的上下文。請添加不起作用的代碼,特別是控制器和序列化程序。還要添加現有的不正確輸出,並給出您想要的輸出示例。 – messanjah

+0

添加了示例代碼 –

+0

您是否嘗試向ReservationSeatSerializer添加'belongs_to'? – SteveTurczyn

回答

1

的JSON API SPEC希望您只包括關係的類型和標識,以減少響應數據和數據庫的請求。如果您想要包括相關的對象,你必須包括它:

ActiveModelSerializer例子:

render json: @reservation, include: '*' 

這包括所有的關係遞歸。這些相關對象將以included陣列結尾。請看JSON API specactive_model_serializer docs

0

你可以試着將你的協會的串行它裏面:

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 
+0

仍然沒有工作它返回相同 「關係」:{ 「預約席」:{ 「數據」: { 「ID」: 「1」, 「類型」: 「預約席」 } ] } –

相關問題