【问题标题】:How to hide created_at and updated_at when using ActiveModel::Serializer使用 ActiveModel::Serializer 时如何隐藏 created_at 和 updated_at
【发布时间】:2017-05-27 20:01:42
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 用更多的上下文来回答这个问题会容易得多。请添加不起作用的代码,尤其是控制器和序列化程序。还要添加现有的错误输出,并给出您想要的输出示例。
  • 添加示例代码
  • 您是否尝试将belongs_to 添加到ReservationSeatSerializer 中?

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


【解决方案1】:

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

ActiveModelSerializer 示例:

render json: @reservation, include: '*'

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

看看JSON API specactive_model_serializer docs

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 仍然不工作它返回相同的“关系”:{“reservation-seats”:{“data”:[{“id”:“1”,“type”:“reservation-seats”} ] }
    猜你喜欢
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2011-06-11
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多