我正在使用Rails创建包含基本待办事项信息的API:名称,列表和项目。我希望它返回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的^代码。
当我查看我的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 guide,rendering和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.application.routes.draw做
namespace :api, defaults: { format: :json } do
resources :users do
resources :lists
end
end
end
如果我能更好地澄清,请告诉我。谢谢!