ActiveModelSerializers gem:如何将参数传递给序列化程序

时间:2016-06-26 19:26:43

标签: ruby-on-rails ruby json active-model-serializers

我正在将gem active_model_serializers从版本0.9.5更新为0.10.1。对于0.9.5版,下面的代码有效。

控制器:

def create
  ...
  render json: @dia, app_rights: app_rights(@dia)
end

串行:

class Api::V1::SerializerWithSessionMetadata < ActiveModel::Serializer
  attributes :app_rights
  def app_rights
    serialization_options[:app_rights]
  end
end

版本0.10.1中已弃用方法serialization_options

  • Here建议改为使用instance_options
  • Here建议使用options:“instance_options仅在主分支中可用,而不在当前RC中。在当前RC中,您必须使用选项”。
  • 还有@options@instance_options的建议。

我尝试用上述所有选项替换serialization_options。但是,在所有情况下,在更新gem之后,生成的json不包括app_rights。我做错了什么?

1 个答案:

答案 0 :(得分:4)

使用instance_options,您的序列化程序应如下所示:

class Api::V1::SerializerWithSessionMetadata < ActiveModel::Serializer
    attributes :app_rights
    def app_rights
        @instance_options[:app_rights]
    end
end

为确保调用正确的序列化程序,您可以像这样呈现特定的序列化程序(否则它将呈现@dia上为类定义的任何内容):

render json: @dia, serializer: SerializerWithSessionMetadata, app_rights: app_rights(@dia)
相关问题