【发布时间】:2016-08-03 00:55:54
【问题描述】:
我在我的 rails 应用程序中使用 Active 模型序列化程序,我想重构显示:
每当我去http://localhost:3000/api/users/1时,我都会看到:
{"data":{"id":"1","type":"users","attributes":{"username":"Iggy1"},"relationships":{"items":{"data":[{"id":"1","type":"items"},{"id":"7","type":"items"}]},"lists":{"data":[{"id":"1","type":"lists"},{"id":"8","type":"lists"},{"id":"14","type":"lists"},{"id":"15","type":"lists"},{"id":"17","type":"lists"}]}}}}
我怎样才能让它看起来像:
{
"data": {
"id": "1",
"type": "users",
"attributes": {
"username": "Iggy1"
},
"relationships": {
"items": {
"data": [{
"id": "1",
"type": "items"
}, {
"id": "7",
"type": "items"
}]
},
"lists": {
"data": [{
"id": "1",
"type": "lists"
}, {
"id": "8",
"type": "lists"
}, {
"id": "14",
"type": "lists"
}, {
"id": "15",
"type": "lists"
}, {
"id": "17",
"type": "lists"
}]
}
}
}
}
我花了很多时间浏览adapters、rendering、architecture,但我找不到指南。首先,是否可以让它看起来像上面的第二个代码块?其次,如果可以的话,我必须怎么做才能改变显示?
api/users_controller.rb
def show
@user = User.find_by(id: params[:id])
@no_user_found = User.all #other alternative when user ID not found?
if @user.nil?
flash[:notice] = "No user found"
render json: @no_user_found, each_serializer: UserSerializer
else
render json: @user, each_serializer: UserSerializer
end
end
user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :username#, :email
has_many :items, through: :lists
has_many :lists
end
routes.rb
Rails.application.routes.draw do
ActiveModelSerializers.config.adapter = :json_api
namespace :api, defaults: { format: :json } do
resources :users do
resources :lists
end
resources :lists, only: [] do
resources :items, only: [:create, :index, :show, :update]
end
resources :items, only: [:destroy]
end
end
【问题讨论】:
-
只是澄清一下,您的问题是如何使一行输出到带有行缩进的 json 输出?
-
目前显示的是单行。我想“修复”显示以包含缩进和换行符。
-
我猜你正在浏览器上显示它。你为什么不使用Postman
-
我会调查 Postman;我以前听说过 :) 是的,我正在从浏览器中查看它;是否可以在浏览器中包含缩进和换行符?
-
我在下面添加了答案。
标签: ruby-on-rails json api active-model-serializers