Active_model_serializers: `meta` repeats when the model contains a `meta` attribute

Created on 12 Apr 2016  路  4Comments  路  Source: rails-api/active_model_serializers

Description

If a model contains a meta attribute or method, it's repeated twice when the JSON renders (see below). This also happens if a model has a meta:jsonb attribute column.

A simple Todo model serializer

class TodoSerializer < ActiveModel::Serializer
  attributes :id, :title, :description, :meta

  def meta
    {
      created: object.created_at,
      updated: object.updated_at,
      done: object.done
    }
  end
end

The #show controller action:

class TodosController < ApplicationController
  def show
    todo = Todo.find(params[:id])
    render json: todo
  end
end

Response looks like this:

{
    "todo": {
        "id": 1,
        "title": "Example Todo",
        "description": "Example description",
        "meta": {
            "created": "2016-04-12T08:24:58.336Z",
            "updated": "2016-04-12T08:24:58.336Z",
            "done": false
        }
    },
    "meta": {
        "created": "2016-04-12T08:24:58.336Z",
        "updated": "2016-04-12T08:24:58.336Z",
        "done": false
    }
}

It seems that the model meta overwrites the ActiveModelSerializer one.

Environment

Clean Rails 4.2.6 installation and active_model_serializers 0.9.4

Needs Bug Verification 0.9.x

All 4 comments

First of all, the recommended way to overwrite an attribute is as follows:

attribute :meta do
  {
      created: object.created_at,
      updated: object.updated_at,
      done: object.done
    }
end

I suspect your issue might go away if you do as suggested above, but the current behavior should clearly be improved to be more intuitive.

@beauby that's not possible with 0.9.4, is it?

Oh, right, I didn't pay attention to the fact that this was a 0.9 issue. Please disregard my above comment.

Thanks for adding this to the list @beauby

Was this page helpful?
0 / 5 - 0 ratings