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

时间:2017-05-27 20:01:42

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

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

基本上对于关联我只想要返回几个属性。

由于

2 个答案:

答案 0 :(得分:1)

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

ActiveModelSerializer示例:

reinterpret_cast

这包括递归的所有关系。这些相关对象最终会出现在render json: @reservation, include: '*' 数组中。

查看JSON API specactive_model_serializer docs

答案 1 :(得分: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