JSON rendering with activemodel serializer in Rails

10,899

Solution 1

Product Controller

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

Product Serializer - app/serializers/products_serializer.rb

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

end

Solution 2

def index
   render json: Product.all, only: [:id, :title]
end
Share:
10,899
Toshi
Author by

Toshi

Updated on June 13, 2022

Comments

  • Toshi
    Toshi almost 2 years

    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.

    The ideal is something like:

    "products": [
      {
        "id": 1,
        "title": "Digital Portable System",
    
      },
      {
        "id": 2,
        "title": "Plasma TV",
      }
    
    ]
    

    However what I got so far is; enter image description here

    My code is simple;

    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
    
  • Francois
    Francois over 6 years
    What is the root: false for?
  • 7urkm3n
    7urkm3n over 6 years
    @Francois , it gives root name in default, smth like if product table {products: [...]} that products is root name. But on version <0.10.x root doesnt work i think. root: false just removes, the products key name and keeps it {[...]}.