如何为嵌入对象指定不同的根名称?

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

在我的应用程序中,我有 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' 的别名?

只需在您的序列化程序中定义一个名为用户和 return 作者的方法,即

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

def users
  object.authors
end

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