【问题标题】:jsonapi-rb Relationships Examplejsonapi-rb 关系示例
【发布时间】:2018-01-17 17:27:42
【问题描述】:

我正在尝试获取一个看起来像这样的 JSON

{
   "data" : {
     "type": "field_definition",
     "id": 5,
     "attributes": {
        "specifier": "foo",
        "entity_type": "bar"
     }
     "relationships": {
        "active_collections" : [1,2,3]
     }
   }
}

我做了一个测试类,我用它作为我的模型:

  class Test
     attr_reader :id,
              :specifier,
              :entity_type,
              :active_collections

      def initialize
        @id = 5
        @specifier = "foo"
        @entity_type = "bar"
        @active_collections = [1,2,3]
      end
    end

我的序列化器:

class SerializableFieldCollection < JSONAPI::Serializable::Resource
  type 'field_collection'

  attributes :specifier, :entity_type

  has_many :active_collections 
end

我把所有东西都称为

  def index
    render jsonapi: Test.new,
           class:   SerializableFieldCollection,
           status:  200   
  end


{"data"=>
  {"id"=>"5", "type"=>"field_collection", "attributes"=>{"specifier"=>"foo", "entity_type"=>"bar"}, "relationships"=>{"active_collections"=>{"meta"=>{"included"=>false}}}}}

有人能指出正确的方向吗?如何使用 jsonapi-rb gem 中的关系/has_many 函数?

【问题讨论】:

    标签: ruby-on-rails json-api


    【解决方案1】:

    我认为您的问题是关于{"meta"=&gt;{"included"=&gt;false}} 部分,您更愿意成为{"data"=&gt;[{ "type": "foo", "id": "1" },{ "type": "foo", "id": "2" }, ...]}? 如果是这样,则默认行为是仅在包含关系时才序列化关系的链接数据。要在响应中包含关系,请使用 include 渲染器选项。

    例子:

    render jsonapi: Test.new,
           class:   SerializableFieldCollection,
           include: 'active_collections',
           status:  200   
    

    【讨论】:

    • 如果您确实想要不包含链接记录的链接数据,您可以将linkage always: true 添加到关系块中
    【解决方案2】:

    您是否验证了JSONAPI::Serializable::Resource 实现了ActiveModelActiveRecord?如果没有,我认为您不能在这里使用has_many。你对ActiveCollection的定义在哪里?

    【讨论】:

    • 我认为JSONAPI::Serializable::Resource 有它自己与ActiveRecord 无关的元素?根据jsonapi-rails提供的文档has_many是正确的使用方法
    • has_many 确实是JSONAPI::Serializable::Resource DSL 的一部分。
    猜你喜欢
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2018-11-07
    • 2015-11-30
    • 2018-12-17
    • 2016-01-07
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多