【问题标题】:rails active model serializer not doing anythingrails active 模型序列化程序没有做任何事情
【发布时间】:2015-04-28 22:03:45
【问题描述】:

我正在使用此处找到的 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

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby serialization


    【解决方案1】:

    您的查询是错误的 - 我猜因为您正在定义 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 对象数组,你需要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
    

    【讨论】:

    • 不要在 Rails 中使用.select('*')。这是一种反模式。默认情况下,Rails 会选择表中的所有列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2012-09-07
    相关资源
    最近更新 更多