Сериализаторы активной модели Rails — JSON API

Я использую AMS версии 0.10 и хочу использовать спецификацию 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"}}}}}

Я хотел бы знать, как получить раздел «включено» для вложенного ресурса.

Пример (из 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"
   }
},

Я никогда раньше не использовал AMS, поэтому любая помощь будет принята с благодарностью.

Большое спасибо


person Dudedolf    schedule 03.10.2016    source источник


Ответы (1)


Просто для всех остальных решение находится здесь https://github.com/rails-api/active_model_serializers/blob/master/docs/jsonapi/schema.md.

По сути, я добавляю следующее к моему действию контроллера (GET products/1)

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

Это позволит запрашивающей системе определить, хотят ли они включить вложенные модели, добавив параметр include='user' для обработки API.

Спасибо

person Dudedolf    schedule 08.11.2016