我正在使用 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":"洗碗","Completed":true},{"id":7,"list_id":1,"name":"完成此作业","completed":false}],"lists":[{"id":1,"name":"重要!","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
根据 AMS readme .
关于ruby-on-rails - Rails Active 模型序列化器返回数组而不是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38669025/