【问题标题】:How to specify a different root name for the embedded objects?如何为嵌入对象指定不同的根名称?
【发布时间】:2015-06-09 13:17:46
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails ember.js ember-data active-model-serializers


    【解决方案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" }
     ]
    }
    

    【讨论】:

    • 我知道,但是当所有东西都可以在一个中提取时,为什么还要提取附加内容。我发送了该数据,但 Ember 无法识别它,因为它使用的密钥超出了预期。
    • 您在混合不同的问题。异步并不意味着只获取一个或不获取。在你的有效载荷authors 之后 blog_posts 看起来不错。但是里面blog_posts你使用author_id(没有嵌入完整的author),所以你必须设置{async: true}。
    • 我已经检查过了,这不是我的意思。 async 表示它将对每个请求的项目进行子请求(何时以及如果需要)。我想要的是 Ember 将使用当前有效载荷中的数据来获取有关 Users 的信息。
    • 哦,我明白你的意思。我将删除答案。对此感到抱歉。
    【解决方案2】:

    只需在您的序列化程序中定义一个名为 users 的方法并在其中返回作者,即

    attributes :id, :title, :text, :created_at, :updated_at, :users
    
    def users
      object.authors
    end
    

    【讨论】:

    • 文章有一位作者,我也希望它被命名为author(因为文章有作者而不是用户)。
    • 好吧,无论你想要什么结构,你都可以在一个方法中实现它:def author ... enddef author_id ... end,只需将方法添加到属性中,你就会拥有你想要的任何命名空间。
    • 但是响应将具有无效的结构。我只想使用有效载荷中的数据来加载Users。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多