mardi 9 juin 2015

Ember model has different name than relation

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?

Aucun commentaire:

Enregistrer un commentaire