在我的应用中,我有BlogPost
模型和User
模型,它们通过名为author
的关系相关联。要从我的Rails应用程序提供数据,我使用active_model_serializers
定义:
class Blog::PostSerializer < ActiveModel::Serializer
embed :ids, include: true
attributes :id, :title, :text, :created_at, :updated_at
has_one :author
has_many :assets
end
当我使用Ember模型获取它时:
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')
});
有一个错误:
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 })`)
这是由我的回复引起的:
{
'blog_posts': [
{
id: 1,
author_id: 1
},
// …
],
'authors': [
{ id: 1, /* … */ }
]
}
有没有办法更改'authors'
以回复'users'
或使用'authors'
作为序列化程序中'users'
的别名?
答案 0 :(得分:1)
来自active_model_serializers 0.8
说明:https://github.com/rails-api/active_model_serializers/tree/0-8-stable
您还可以为嵌入对象指定不同的根,而不是用于引用它们的键:
class PostSerializer < ActiveModel::Serializer
embed :ids, :include => true
attributes :id, :title, :body
has_many :comments, :key => :comment_ids, :root => :comment_objects
end
这将生成如下所示的JSON:
{"post": {
"id": 1,
"title": "New post",
"body": "A body!",
"comment_ids": [ 1 ]
},
"comment_objects": [
{ "id": 1, "body": "what a dumb post" }
]
}
答案 1 :(得分:0)
只需在序列化程序中定义一个名为users的方法,然后在其中返回作者即
_matchingData