0

How can I check the serialization of an active model serializer in the command line?

$ rails c
> ModelSerializer.new(Model.last)
=> # does not give me the custom format of my serializer
steel
  • 11,883
  • 7
  • 72
  • 109

2 Answers2

3

You are missing the call to to_json.

ModelSerializer.new(Model.last).to_json

to properly view it in irb use puts

puts ModelSerializer.new(Model.last).to_json

You can also use as_json or serializable_attributes to get the attributes as Hash. Not surprisingly, these methods use the same naming of the built-in serialization methods in an ActiveRecord model.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Thanks @simone, I had missed that. Do you know of any methods added directly to the model that would produce the same output? e.g. Model.last.serialized_json ? – steel Oct 09 '15 at 14:24
  • 1
    Please beware that the method `to_json` from the model is not the same of `to_json` from a serializer object. In fact, the purpose of the serializer is to avoid using those model built-in serialization methods that are not a good practice. – Simone Carletti Oct 09 '15 at 14:47
  • What if you need to pass a `serialization_scope` to the serializer? In a controller, the serializer is given `current_user`, but I cannot figure out how to provide a scope in the command line. – nerfologist Sep 28 '17 at 08:07
1

Note that if you are using AMS version 0.10.x, you need to do the following to get the hash from outside a Rails controller:

ActiveModel::SerializableResource.new(Model.last).serializable_hash
beauby
  • 550
  • 3
  • 11