How to specify a different root name for the embedded objects?

106 views Asked by At

In my app I had BlogPost model and User model that are related through relation named author. To serve data from my Rails app I use active_model_serializers with definition:

class Blog::PostSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :title, :text, :created_at, :updated_at

  has_one :author
  has_many :assets
end

When I fetch this using Ember model:

Admin.BlogPost = DS.Model.extend({
  author:     DS.belongsTo('User'),

  title:      DS.attr('string'),
  text:       DS.attr('string'),
  createdAt:  DS.attr('date'),
  updatedAt:  DS.attr('date')
});

There is an error:

Uncaught Error: Assertion Failed: You looked up the 'author' relationship on a 'blog.post' with id 1 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)

Which is caused by that my response looks like:

{
  'blog_posts': [
    {
      id: 1,
      author_id: 1
    },
    // …
  ],
  'authors': [
    { id: 1, /* … */ }
  ]
}

Is there any way to change 'authors' in response to 'users' or use 'authors' as alias to 'users' in serializer?

2

There are 2 answers

4
artych On BEST ANSWER

From active_model_serializers 0.8 description: https://github.com/rails-api/active_model_serializers/tree/0-8-stable

You can also specify a different root for the embedded objects than the key used to reference them:

class PostSerializer < ActiveModel::Serializer
  embed :ids, :include => true

  attributes :id, :title, :body
  has_many :comments, :key => :comment_ids, :root => :comment_objects
end

This would generate JSON that would look like this:

{"post": {
    "id": 1,
    "title": "New post",
    "body": "A body!",
    "comment_ids": [ 1 ]
 },
 "comment_objects": [
  { "id": 1, "body": "what a dumb post" }
 ]
}
3
nesiseka On

Just define a method in your serializer named users and return authors in it I.e.

attributes :id, :title, :text, :created_at, :updated_at, :users

def users
  object.authors
end