Tos*_*shi 5 json ruby-on-rails active-model-serializers
我只是想知道rails如何使用JSON中的activemodel-serializer渲染模型对象.我安装了activemodel-serializer但是输出有所不同.
理想是这样的:
"products": [
{
"id": 1,
"title": "Digital Portable System",
},
{
"id": 2,
"title": "Plasma TV",
}
]
Run Code Online (Sandbox Code Playgroud)
我的代码很简单;
class Api::V1::ProductsController < ApplicationController
before_action :authenticate_with_token!, only: [:create, :update, :destroy]
respond_to :json
def index
respond_with Product.all
end
def show
respond_with Product.find(params[:id])
end
def create
product = current_user.products.build(product_params)
if product.save
render json: product, status: 201, location: [:api, product]
else
render json: { errors: product.errors }, status: 422
end
end
def update
product = current_user.products.find(params[:id])
if product.update(product_params)
render json: product, status: 200, location: [:api, product]
else
render json: { errors: product.errors }, status: 422
end
end
def destroy
product = current_user.products.find(params[:id])
product.destroy
head 204
end
private
def product_params
params.require(:product).permit(:title, :price, :published)
end
end
Run Code Online (Sandbox Code Playgroud)
7ur*_*m3n 12
def index
render json: Product.all, each_serializer: ProductsSerializer, root: false
end
Run Code Online (Sandbox Code Playgroud)
app/serializers/products_serializer.rbclass ProductsSerializer < ActiveModel::Serializer
attributes :id, :title
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5440 次 |
| 最近记录: |