【问题标题】:Parsing Included Associations from JSON API response - Rails API, AMS, Vue.js SPA从 JSON API 响应解析包含的关联 - Rails API、AMS、Vue.js SPA
【发布时间】:2017-06-03 08:10:48
【问题描述】:

我有一些数据位于(攀爬)区域的树/层次模型中,它们通过父区域和子区域关联。

将 JSON API 适配器与我的 Active Model Serializer 一起使用,

class AreaSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :location, :slug
  belongs_to :user
  belongs_to :parent
  has_many :children
end

我可以返回包含在我的控制器中的父级和子级的区域:

class AreasController < ApplicationController

  ...

  def show
    area = Area.friendly.find(params[:id])
    render json: area, include: [:children, :parent]
  end
end

并准确返回预期内容:具有区域数据的 JSON 响应,一个标识 user_id/type、parent_id/type、children_id/type 的关系对象。这一切都被发送到 Vuex 商店中的一个变异,用于 Vue SPA。

问题是响应的included 成员中的所有内容都混淆了。我最终希望轻松访问parent "slug" 并分别存储children 数组。

是的,响应中包含子项和父项,但它们都是相同的type: "areas",并且都在一个数组中。必须有一些合理的方法在javascript中解析这些数据,这样我就可以将响应的relationships成员中的parent: data { id: "5" }included数组成员之一的id进行比较

我知道,如果我放弃 JSON API 规范并只使用默认序列化程序,我可以使这更容易,这将在响应数据中直接为我提供 parentchildren 属性。

有什么方法可以将 javascript 中的这些相关对象解析为它们自己明确定义的数组/对象?也许我应该放弃这个 JSON API 规范,直接从服务器控制我的数据输出?

我希望这是有道理的;以前一定有人遇到过这种情况,但我找不到任何例子......

【问题讨论】:

    标签: javascript ruby-on-rails json vue.js active-model-serializers


    【解决方案1】:

    您可以手动解析响应对象:

    // User response from server:
    
    const user = {
      "id": "1",
      "type": "users",
      "attributes": {
        "name": "John Doe"
      },
      "included": [
        {
          "id": "2",
          "type": "roles",
          "attributes": {
            "name": "Admin"
          }
        }
      ]
    };
    
    // Manually parsing a User response object:
    user.id; // 1
    user.attributes.name; // John Doe
    user.included.filter(obj => obj.type === 'roles')[0].attributes.name; // Admin
    

    或者,您可以使用 JSONAPI 套件:https://jsonapi-suite.github.io/jsonapi_suite/js/home

    【讨论】:

      【解决方案2】:

      首先你应该修复你的序列化器

      你的关系 has_many :children 是错误的,你应该用 has many :childrens 修复它

      因为你有很多孩子而不是孩子!!!

      第二个你可以改变包含关系和改变显示定义

      def show
        area = Area.friendly.find(params[:id])
        render jsonapi: area, include: %w(childrens, parent)
      end
      

      可能是工作!!!

      【讨论】:

        猜你喜欢
        • 2013-08-20
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-27
        相关资源
        最近更新 更多