active_model_serializer: 如何在命令行中测试?

active_model_serializer: How to test in the command line?

如何在命令行中检查活动模型序列化程序的序列化?

$ rails c
> ModelSerializer.new(Model.last)
=> # does not give me the custom format of my serializer

您未接来电 to_json

ModelSerializer.new(Model.last).to_json

要在 irb 中正确查看它,请使用 puts

puts ModelSerializer.new(Model.last).to_json

您也可以使用 as_jsonserializable_attributes 来获取 Hash 的属性。毫不奇怪,这些方法在 ActiveRecord 模型中使用与内置序列化方法相同的命名。

请注意,如果您使用的是 AMS 版本 0.10.x,您需要执行以下操作以从 Rails 控制器外部获取哈希:

ActiveModel::SerializableResource.new(Model.last).serializable_hash