本文介绍了在Rails中使用ActiveModel序列化器进行JSON渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道Rails如何使用JSON中的activemodel-serializer渲染模型对象.我安装了activemodel-serializer,但输出有所不同.

I just wonder how the rails render the model objects with activemodel-serializer in JSON.I installed activemodel-serializer but the output is something different.

理想是这样的:

"products": [
  {
    "id": 1,
    "title": "Digital Portable System",

  },
  {
    "id": 2,
    "title": "Plasma TV",
  }

]

然而,到目前为止我得到了什么;

However what I got so far is;

我的代码很简单;

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

推荐答案

产品控制器

def index
   render json: Product.all, each_serializer: ProductsSerializer, root: false
end

产品序列化器-app/serializers/products_serializer.rb

class ProductsSerializer < ActiveModel::Serializer
  attributes :id, :title

end

这篇关于在Rails中使用ActiveModel序列化器进行JSON渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 12:41