Active_model_serializers: Easiest way to serialized outside of a controller?

Created on 10 Jun 2015  路  4Comments  路  Source: rails-api/active_model_serializers

Currently, it seems like the best way to serialize outside a controller with the JSON adapter is

serializer = PostSerializer.new(post)
adapter = ActiveModel::Serializer::Adapter.create(serializer)

# output
adapter.to_json

Is this is the most direct way to do it? Or perhaps any recommendations?

Most helpful comment

@axsuul instead .to_json use . as_json.
But as @bf4 said, why are you trying to serialize it outside the controller?
If possible, could you try to create this question at Stackoverflow and send over the link? We are trying to focus the questions there :smile: I'm closing it for now

All 4 comments

that's close enough.. see how I wrote some tests here https://github.com/rails-api/active_model_serializers/issues/878#issuecomment-96073030 (but why are you serializing outside of the controller). the tl;dr of how AMS does it is https://github.com/rails-api/active_model_serializers/blob/master/lib/action_controller/serialization.rb#L38-L48

@axsuul instead .to_json use . as_json.
But as @bf4 said, why are you trying to serialize it outside the controller?
If possible, could you try to create this question at Stackoverflow and send over the link? We are trying to focus the questions there :smile: I'm closing it for now

I'm trying to send a json object to a webhook, using the same serializer that I return as an API response. Hope that makes sense, and thanks for the responses!

Manual serializing is also useful if you're using the react_component helper that ships with React-Rails.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Andriykoo picture Andriykoo  路  5Comments

yjukaku picture yjukaku  路  5Comments

Tybot204 picture Tybot204  路  3Comments

preist picture preist  路  4Comments

seoyoochan picture seoyoochan  路  4Comments