简体   繁体   中英

Is it possible to use ActiveModel::Serializers outside of Rails controller?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM