ember.js – 在EmberJS中使用Rails active_model_serializers在非标准类名中加载对象

前端之家收集整理的这篇文章主要介绍了ember.js – 在EmberJS中使用Rails active_model_serializers在非标准类名中加载对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Rails中有一些模型看起来像这样:
class Issue < ActiveRecord::Base
  belongs_to :reporter,class_name: 'User'
  belongs_to :assignee,class_name: 'User'
  has_many :comments
end

class User < ActiveRecord::Base
end

class Comment < ActiveRecord::Base
end

像这样的序列化器:

class IssueSerializer < ActiveModel::Serializer
  attributes :id
  embed :ids,include: true

  has_one :reporter,:embed => :ids
  has_one :assignee,:embed => :ids
end

class UserSerializer < ActiveModel::Serializer
  attributes :id,:name
end

class CommentSerializer < ActiveModel::Serializer
  attributes :id,:body
end

这会生成类似于以下内容的JSON:

{
  "issues": [
    {
      "id": 6,"reporter_id": 1,"assignee_id": 2,"comment_ids": [
        3
      ]
    },],"comments": [
    {
      "id": 3
      "body": "Great comment"
    }
  ],"reporters": [
    {
      "id": 1
      "name": "Ben Burton"
    }
  ],"assignees": [
    {
      "id": 2
      "name": "Jono Mallanyk"
    }
  ]
}

问题是侧载报告人和受让人JSON对象不被Ember识别为User对象,我看到以下错误

Uncaught Error: assertion Failed: Your server returned a hash with the key reporters but you have no mapping for it

我不想删除

embed :ids,include: true

来自我的IssueSerializer,因为那时评论不会被序列化.

我考虑过有几种可能解决这个问题的方法

>如果ActiveModel :: Serializer的embed方法在其include选项中接受了模型列表,则可以将JSON响应过滤为仅包含侧载注释.
> Ember数据的模型可以配置为从“用户”,“记者”和“受让人”侧面加载用户……但据我所知,从源代码来看,它似乎只支持sideloadAs的一个密钥.
>以某种方式忽略/禁用未知密钥的侧载错误(可能是最不理智的方法).

我还缺少另一种选择吗?我想我可能必须写一个修复程序并向pull-api / active_model_serializers,emberjs / data或两者提交pull请求.

编辑:我的临时解决方法是将IssueSerializer更改为仅序列化记者和受让人的ID:

class IssueSerializer < ActiveModel::Serializer
  attributes :id,:reporter_id,:assignee_id
  embed :ids,include: true

  has_many :comments,:embed => :ids
end

解决方法

我有类似的问题,并在 ActiveModel::Serializers readme找到解决方案.您可以使用:root选项.尝试类似这样的问题串行器:
class IssueSerializer < ActiveModel::Serializer
  attributes :id
  embed :ids,:root => "users"
  has_one :assignee,:root => "users"
  has_many :comments
end

猜你在找的JavaScript相关文章