Search code examples
ruby-on-railsruby-on-rails-5active-model-serializers

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


I'm using active_model_serializers in rails application it's working perfectly fine, but when dealing with associations it's returning all the attributes of the associated model (including the created_at and updated_at) which I don't want to be returned.

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

I tried creating a new file as well, where I have defined the attributes which needed to returned, but in this case it's just returning type only.

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

this is resulting in:

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

Basically for the association I only want few attributes to be returned.

Thanks


Solution

  • The JSON API spec wants you to reduce the response data and database requests by just including the type and identifier of the relation. If you want to include the related object, you have to include it:

    ActiveModelSerializer Example:

    render json: @reservation, include: '*'
    

    This includes all the relationships recursively. These related objects will end up in the included array.

    Take a look at the JSON API spec and the active_model_serializer docs.