2016-07-29 17 views
2

Railsを使用して、基本的なToD情報(名前、リスト、アイテム)を含むAPIを作成しています。Railsアクティブモデルシリアライザはjsonの代わりに配列を返します

{ 
    "data": [ 
    { 
     "type": "posts", 
     "id": "1", 
     "attributes": { 
     "title": "JSON API is awesome!", 
     "body": "You should be using JSON API", 
     "created": "2015-05-22T14:56:29.000Z", 
     "updated": "2015-05-22T14:56:28.000Z" 
     } 
    } 
    ], 
    "links": { 
    "href": "http://example.com/api/posts", 
    "meta": { 
     "count": 10 
    } 
    } 
} 

^Active Serializer's Githubからコード:私はそれがこのような何かを見て、JSON形式を返すようにしたいです。

私は私のlocalhostのhttp://localhost:3000/api/users/に見ると、それはそれは、ハッシュの配列を返す

[{"id":1,"username":"Iggy1","items":[{"id":1,"list_id":1,"name":"Wash dishes","completed":true},{"id":7,"list_id":1,"name":"Finish this assignment","completed":false}],"lists":[{"id":1,"name":"Important!","user_id":1,"permission":"private"},...

を示しています。私はシリアライザをセットアップするときに重要なステップを逃したと確信しています。ハッシュの配列をJSON API形式に再フォーマットするにはどうすればよいですか?

私はgetting started guiderendering、およびJSON APIセクションを読んだことがありますが、それでもわかりませんでした。私はそれを見落としたかもしれない。

私のコードの一部:

アプリ/シリアライザ/ user_serializer.rb

class UserSerializer < ActiveModel::Serializer 
    attributes :id, :username#, :email 
    has_many :items, through: :lists 
    has_many :lists 
end 

アプリ/コントローラ/ API/users_controller.rb

def index 
    @users = User.all 
    render json: @users, each_serializer: UserSerializer 
    end 

ルート Rails.applic ation.routes.draw do

namespace :api, defaults: { format: :json } do 

    resources :users do 
     resources :lists 
    end 
    end 
end 

私はそれをより明確にすることができますか教えてください。ありがとう!!

+2

JSON APIアダプターを使用すると宣言しましたか?あなたの設定で 'ActiveModelSerializers.config.adapter = ActiveModelSerializers :: Adapter :: JsonApi'を設定する必要があります。手順[ここをクリック](https://github.com/rails-api/active_model_serializers/blob/master/docs/general/adapters.md#jsonapi) – chrismanderson

+1

それは働いた!ありがとうございました :)。私はそれをどこに置くべきか分からなかった。 – Iggy

答えて

2

(コメントからの回答)

は、JSONのAPIアダプタを使用するには、あなたがそれを使用したい宣言する必要があります。

ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi 

AMS readmeによると、

関連する問題