ActiveModelSerializer 【Rails】
I’ve used active_model_serializer in Rails for the first time. It has many merits but, it entails some techniques. So, I’ve summarized them here in order not to forget them.
What is active_model_serializer?
Document is here.
It is gem which returns json from server code. This is popular and necessary if you use json in Rails application.
Merits?
There are three big merits for using active_model_serializer
1.The response is fast.
When you use json in rails application, you will adopt jbuilder. However, it takes much time to render partial in that case. It makes users annoyed, but if you use active_model_serializer, you can decide related objects with ‘has_many’ and ‘has_one’. That’s why, the response becomes faster.
2.You can write code like Rails.
How to write code becomes like Rails. When you use jbuilder,
json.title @post.title
json.body @post.body
it is like above. It is difficult to understand, at least, it is not Ralis. If you use active_model_serializer, you can solve this issue.
3. You can limit returned json attributes.
If your returned json has secure things(ex. key code and password...), your application is so dangerous. You can choose attributes to be returned with active_model_serializer.
How to use
For example, you have BooksController which returns books object(attributes are title and authors) json. And the books are written by many authors. In that case, the controller code is like below.
class Api::V1::BooksController < Api::ApiController
def index
render json: books, each_serializer: Api::V1::BookSerializer, include: [‘authors’]
end
end
And the serializer is like this.
class Api::V1::BookSerializer < ActiveModel::Serializer
attributes :id, :title #limit attributes
has_many :authors #related object
end
Wrap up
Wit active_model_serializer, you can write code which returns json easily. There are many other benefit techniques. Please refer to the document.