ActiveModelSerializers gem:如何将参数传递给序列化程序
ActiveModelSerializers gem: how to pass parameter to serializer
我正在将 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
方法 serialization_options
已在 0.10.1 版中弃用。
- Here建议使用
instance_options
代替
- Here建议使用
options
:"instance_options is only available in the master branch, not in the current RC. In the current RC, you have to use options instead".
- 还有
@options
和 @instance_options
的建议。
我已经尝试用以上所有选项替换 serialization_options
。但是,在所有情况下,更新 gem 后,生成的 json 不包括 app_rights
。我做错了什么?
使用 instance_options,您的序列化程序应如下所示:
class Api::V1::SerializerWithSessionMetadata < ActiveModel::Serializer
attributes :app_rights
def app_rights
@instance_options[:app_rights]
end
end
为了确保调用正确的序列化程序,您可以像这样呈现特定的序列化程序(否则它将呈现为@dia 上的 class 定义的任何内容):
render json: @dia, serializer: SerializerWithSessionMetadata, app_rights: app_rights(@dia)
我正在将 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
方法 serialization_options
已在 0.10.1 版中弃用。
- Here建议使用
instance_options
代替 - Here建议使用
options
:"instance_options is only available in the master branch, not in the current RC. In the current RC, you have to use options instead". - 还有
@options
和@instance_options
的建议。
我已经尝试用以上所有选项替换 serialization_options
。但是,在所有情况下,更新 gem 后,生成的 json 不包括 app_rights
。我做错了什么?
使用 instance_options,您的序列化程序应如下所示:
class Api::V1::SerializerWithSessionMetadata < ActiveModel::Serializer
attributes :app_rights
def app_rights
@instance_options[:app_rights]
end
end
为了确保调用正确的序列化程序,您可以像这样呈现特定的序列化程序(否则它将呈现为@dia 上的 class 定义的任何内容):
render json: @dia, serializer: SerializerWithSessionMetadata, app_rights: app_rights(@dia)