2016-07-29 97 views
2

我正在使用Rails創建包含基本待辦事項信息的API:名稱,列表和項目。我希望它返回JSON格式,看起來是這樣的:從Active Serializer's GithubRails活動模型序列化程序返回數組而不是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 
    } 
    } 
} 

^代碼。

當我看着在我的本地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 guiderenderingJSON 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

相關問題