0
votes

Here it's my products.controller

  def index
    if params[:page]
      @product = Product.page(params[:page]).per(5)
    else
      @product = Product.order('updated_at DESC')
    end
    render json: {
      status: '200',
      message: 'OK',
      data: ActiveModel::Serializer::CollectionSerializer.new(@product, each_serializer: ProductSerializer)},status: 200
  end

  def show
      render json: {
        status: '200',
        message: 'OK',
        data: ActiveModel::Serializer::CollectionSerializer.new(@product, each_serializer: ProductSerializer)},status: 200
  end

Here my product serializer

class ProductSerializer < AplicationSerializer
  attributes :id, :product_name, :category, :company, :description, :logo_img, :web_link
  belongs_to :category
  has_many :images 
en

d

If I try to access localhost:3000/products/, it can display all the data that I want, but if I want to try localhost:3000/products/1, it's wrong, so what the wrong about my code?

{
    "status": "200",
    "message": "OK",
    "data": [
        {
            "id": 1,
            "product_name": "MDS",
            "category": {
                "id": 4,
                "category": "Market Place",
                "created_at": "2018-04-12T02:58:59.949Z",
                "updated_at": "2018-04-12T02:58:59.949Z"
            },
            "company": "PT Media Data ",
            "description": "ISP di Indo",
            "logo_img": "mds.jpg",
            "web_link": "https://mds.co/",",
            "images": [
                {
                    "id": 1,
                    "link": "http:/mds.com/mds.png"
                },
                {
                    "id": 2,
                    "link": "http:/mds.com/mds.png"
                },
                {
                    "id": 3,
                    "link": "http:/mds.com/mds.png"
                },
                {
                    "id": 4,
                    "link": "http:/mds.com/mds.png"
                }
            ]
        }
    ]
}

in the above is the display I want to display at http://localhost:3000/products/1, but i still got no appear, even though i can display it with same code on def index

Thanks for your help

1
Which error do you have on localhost:3000/products/1? If no errors then what is wrong with it? Where and how do you define @product for show action? What is in your routes.rb for products resource? - Vasilisa

1 Answers

0
votes

The only thing that can seem to be missing here is setting the @product If you have a before_action :show, :set_product this might not be the problem. The other difference is between an array in the index and a single element in the show. you better use ProductSerializer.new(@product).as_json instead of using the collection serializer