I'm using websocket-rails
gem for web-sockets and I would like to use ActiveModel::Serializers for creating JSON payload for web-socket message.
Is it possible to use serializer without using render
in controller?
After looking into source code, I found answer I was looking for.
You can use AMS by explicitly instantiating serializer: ConversationSerializer.new(Conversation.last).as_json
for collection:
ActiveModel::Serializer::CollectionSerializer.new(Conversation.all, serializer: ConversationSerializer).as_json
Yes, it is possible.
Let's say that you have a Product
model and a p
record:
# p = Product.first
ProductSerializer.new(p).to_json
Also, be aware that you may have to load the required files:
require "action_controller"
require "action_controller/serialization"
require "#{Rails.root}/app/serializers/product_serializer.rb"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With