问题
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