gpt4 book ai didi

ember.js - 在 EmberJS 中使用 Rails+active_model_serializers 侧加载具有非标准类名的对象

转载 作者:行者123 更新时间:2023-12-04 12:22:37 26 4
gpt4 key购买 nike

我在 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"
}
]
}

问题是 Ember 无法将侧载的记者和受让人 JSON 对象识别为 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 方法在其包含选项中接受模型列表,则这可以过滤 JSON 响应以仅包含旁加载的注释。
  • Ember 数据的模型可以配置为从“用户”、“报告者”和“受让人”侧加载用户……但据我所知,它似乎只支持 sideloadAs 的一个键。
  • 以某种方式忽略/禁用未知 key 的侧加载错误(可能是最不理智的方法)。

  • 我在这里错过了另一个选择吗?我想我可能需要编写一个修复程序并向 rails-api/active_model_serializers、emberjs/data 或两者提交拉取请求。

    编辑 :我的临时解决方法是将 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, include: true

    has_one :reporter, :root => "users"
    has_one :assignee, :root => "users"
    has_many :comments
    end

    关于ember.js - 在 EmberJS 中使用 Rails+active_model_serializers 侧加载具有非标准类名的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15363333/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com