【发布时间】:2016-07-29 23:56:56
【问题描述】:
我正在使用 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的代码。
当我查看本地主机 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 部分,但我仍然无法弄清楚。我可能忽略了它。
我的一些代码:
app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :username#, :email
has_many :items, through: :lists
has_many :lists
end
app/controllers/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
如果我能更好地澄清它,请告诉我。谢谢!!
【问题讨论】:
-
您是否已声明要使用 JSON API 适配器?需要在您的配置中设置
ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi。说明here -
成功了!谢谢 :)。我以前不知道该放在哪里。
标签: ruby-on-rails json active-model-serializers