代码之家  ›  专栏  ›  技术社区  ›  Rhs

jsonapi rb关系示例

  •  1
  • Rhs  · 技术社区  · 7 年前

    我试图得到一个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中的relationships/has_many函数吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   beauby    7 年前

    我想你的问题是关于 {"meta"=>{"included"=>false}} 部分,你宁愿 {"data"=>[{ "type": "foo", "id": "1" },{ "type": "foo", "id": "2" }, ...]} ? include 渲染器选项。

    例子:

    render jsonapi: Test.new,
           class:   SerializableFieldCollection,
           include: 'active_collections',
           status:  200   
    
        2
  •  0
  •   Stuart    7 年前

    JSONAPI::Serializable::Resource 机具 ActiveModel ActiveRecord ? 如果没有,我认为你不能使用 has_many ActiveCollection ?