rails active模型序列化器没有做任何事情

我正在使用此处找到的GEM: https : //rubygems.org/gems/active_model_serializers

我已经使用rails g创建了序列化程序,将它添加到我返回json的控制器中,但它仍然返回所有内容而不是已定义的属性 – 任何想法?

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 

谢谢。

您的查询是错误的 – 我猜测,因为您正在定义一个show方法,您正在寻找的是这样的:

 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 

如果您真的打算序列化ProductPrice对象数组,则需要传递each_serializer选项 。

 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