rails active model serializer not doing anything

柔情痞子 提交于 2019-12-25 14:05:51

问题


I am using the the GEM found here: https://rubygems.org/gems/active_model_serializers

I've created the serializer using rails g, added it to the controller where I return json but it is still returning everything and not the defined attributes - Any ideas?

module Api
    module V1
        class ProductDetailsController < ApplicationController          
            def show
                @prod = ProductPrice.joins(:product, :retailer).select("*")
                render json: @prod, serializer: ProductDetailSerializer
            end 
        end
    end
end

class ProductDetailSerializer < ActiveModel::Serializer
  attributes :id
end

Thanks.


回答1:


Either your query is wrong - I´m guessing that since you are defining a show method what you are looking for is something like this:

module Api
    module V1
        class ProductDetailsController < ApplicationController          
            def show
                @prod = ProductPrice.joins(:product, :retailer).find(params[:id])
                render json: @prod, serializer: ProductDetailSerializer
            end 
        end
    end
end

If you really intend to serialize an array of ProductPrice objects you need to pass the each_serializer option.

module Api
    module V1
        class ProductDetailsController < ApplicationController          
            def show
                @prod = ProductPrice.joins(:product, :retailer).all
                render json: @prod, each_serializer: ProductDetailSerializer
            end 
        end
    end
end


来源:https://stackoverflow.com/questions/29930777/rails-active-model-serializer-not-doing-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!