【问题标题】:JSON rendering with activemodel serializer in Rails在 Rails 中使用 activemodel 序列化程序进行 JSON 渲染
【发布时间】:2016-11-28 00:11:32
【问题描述】:

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

理想是这样的:

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

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

]

但是到目前为止我得到的是;

我的代码很简单;

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

【问题讨论】:

    标签: ruby-on-rails json active-model-serializers


    【解决方案1】:

    产品控制器

    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
    

    【讨论】:

    • root: false 是干什么用的?
    • @Francois ,它默认给出根名称,就像产品表 {products: [...]} 产品是根名称一样。但是我认为在&lt;0.10.x root 版本上不起作用。 root: false 只是删除产品密钥名称并保留它{[...]}
    【解决方案2】:
    def index
       render json: Product.all, only: [:id, :title]
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-21
      • 2015-08-05
      • 2015-01-25
      • 1970-01-01
      • 2018-04-23
      • 2020-07-06
      • 1970-01-01
      • 2015-11-02
      相关资源
      最近更新 更多