New coders are often surprised when entering new projects that have new technologies, find people to use it very easily, and I struggle to find out. And my difficulty encountered is ActiveModel Serializers. After researching and using, I see Serializers as a magic hand to help data taken from active records, I can manipulate it to fit the data I need. Quite interesting, and useful especially for projects using the Rails API to manipulate Json type data. So this article I want to share for new friends as I can approach the easiest way to understand it as well as initially be able to use and customize the data accordingly.
1. Demo data
Model Relationships
And here is the content of their model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | ## app/models/user.rb class User < ApplicationRecord has_many :mountains has_many :regions end ## app/models/mountain.rb class Mountain < ApplicationRecord belongs_to :user belongs_to :region, optional: true end ## app/models/region.rb class Region < ApplicationRecord has_many :mountains belongs_to :user end |
We will start with the
Index
and Show
actions in Restful and they are almost the same:1 2 3 4 5 6 7 8 | ## app/controllers/users_controller.rb class UsersController < ApplicationController def index render json: User.all end def show render json: User.find(params |