2016-10-03 2 views
0

Ich bin mit AMS-Version 0.10 und suche die json-API-Spezifikation zu verwenden, um meine Antworten zu machen. Allerdings habe ich Schwierigkeiten, den 'included' Schlüssel für meine Beziehungsdaten darzustellen. Ich habe folgendes Setup:Rails Aktive Modell Serializer - JSON Api

products_controller.rb

class Api::V1::ProductsController < ApplicationController 
... 
respond_to :json 

def show 
    respond_with Product.find(params[:id]) 
end 
... 

product_serializer.rb

class ProductSerializer < ActiveModel::Serializer 
    attributes :id, :title, :price, :published 
    has_one :user 
end 

user_serializer.rb

class UserSerializer < ActiveModel::Serializer 
    attributes :id, :email, :auth_token, :created_at, :updated_at 
end 

products_controller_spec.rb

before(:each) do  
    @product = FactoryGirl.create :product 
    get :show, params: { id: @product.id } 
end 
... 
it "has the user as a embeded object" do 
    product_response = json_response 
    puts "&&&&&&&&&&&&&&&" 
    puts product_response #output below 

    #expect(product_response[:user][:email]).to eql @product.user.email 
end 
... 

json_response

{:data=>{:id=>"1", :type=>"products", :attributes=>{..working..}, :relationships=>{:user=>{:data=>{:id=>"1", :type=>"users"}}}}} 

Ich möchte wissen, wie die 'enthalten' für die verschachtelte Ressource-Abschnitt zu erhalten.

Beispiel (aus http://jsonapi.org/format/#introduction)

{ 
"data": [{ 
"type": "articles", 
"id": "1", 
"attributes": { 
    "title": "JSON API paints my bikeshed!" 
}, 
"links": { 
    "self": "http://example.com/articles/1" 
}, 
"relationships": { 
    "author": { 
    "links": { 
     "self": "http://example.com/articles/1/relationships/author", 
     "related": "http://example.com/articles/1/author" 
    }, 
    "data": { "type": "people", "id": "9" } 
    } 
}], 
"included": [{ 
    "type": "people", 
    "id": "9", 
    "attributes": { 
    "first-name": "Dan", 
    "last-name": "Gebhardt", 
    "twitter": "dgeb" 
    }, 
    "links": { 
    "self": "http://example.com/people/9" 
    } 
}, 

Ich habe AMS nie zuvor so wird jede Hilfe sehr dankbar verwendet werden.

Vielen Dank

Antwort

0

Gerade für jemand anderes die Lösung ist hier https://github.com/rails-api/active_model_serializers/blob/master/docs/jsonapi/schema.md.

Im Wesentlichen füge ich folgendes meine Controller-Aktion (GET Produkte/1)

render json: product, include: params[:include] 

Dies wird das Anforderungssystem ermöglichen, um zu bestimmen, ob sie die verschachtelten Modelle aufnehmen möchten, indem Sie den Parameter hinzufügen schließen =‘ Benutzer 'für die API zu verarbeiten.

Dank

Verwandte Themen