Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Active Model Serializer without an Active Record Model?

I want to take the results of a pl/pgsql function, that returns a set of records and user AMS to serialize the results. How can I do this?

like image 582
Caleb Sayre Avatar asked Apr 07 '16 19:04

Caleb Sayre


People also ask

What does active model serializer do?

The primary usage of Active Model Serializers is to create custom JSON responses. By default, Rails provides a way to render JSON, but we need a serializer if we want to customize it.

How does serializer work in Rails?

Serialization converts an object in memory into a stream of bytes that can be recreated when needed. Serializers in Ruby on Rails convert a given object into a JSON format. Serializers control the particular attributes rendered when an object or model is converted into a JSON format.

What is Active model in Ruby?

Active Model is a library containing various modules used in developing classes that need some features present on Active Record.

What is serializer in backend?

A serializer is an object responsible for transforming a Model or Collection that's returned from your route handlers into a JSON payload that's formatted the way your frontend app expects. For example, this route handler returns a Movie model: this. get("movies/:id", (schema, request) => { return schema.


1 Answers

AMS can serialize a Plain-Old Ruby Object. AMS provides ActiveModelSerializers::Model which can easily make a PORO a serializable object by doing this:

class MyModel < ActiveModelSerializers::Model
  attributes :id, :name, :level
end

MyModelSerializer would be the default serializer.

like image 102
Caleb Sayre Avatar answered Sep 17 '22 20:09

Caleb Sayre