What is ActiveModel::Serializer
ActiveModel::Serializer or AMS for short is a Powerful tool provided by ruby on rails to allow us to certain how we return data (in my case json data) from our different routes and models and what not and put it in a configuration we can use on the front end.
AMS gives us a way to use macros to render associated data, that can be anything from <include> to <belongs_to> to <has_many>
Its easier to make some examples so let try it like this a normal non sterilizer would look something like this
model:class BBCards< ApplicationRecord belongs_to :Owner
endmodel:
class Owner < ApplicationRecord has_many :BBCards
endControler:
class OwnerController < ApplicationControllerdef index
owner = Owner.all
render json: owner
end
that would return a standard json array with owner data showing all there baseball cards with whatever we have in the card table say its name and scores, postion, averages whatever other baseball stuff.
but it could have a whole bunch of needless data too depending on what you actually wanna return if you only want it to come back with the name you would have to write a bunch of exceptions over and over for each different call in different circumstances. calls like :include or :except to refine what you want but it could get tedious to write that in every single controller action.
With Sterilizer all you have to do is. install the gem and then create one
gem 'active_model_serilizers'
bundle install
rails g serializer Owner
rails g serializer Card
Then we can set up something with the card Owner like
Owner serializer:class OwnerSerializer < ActiveModel::Serializerattributes :id, :name, :cardsdef cards
ActiveModel::SerializableResource.new(object.cards, each_serializer: CardSerializer)
end
endCard serializer:class CardSerializer < ActiveModel::Serializer
attributes :name, :nickname, :team
end
This will allow us to only have the cards name, nickname, and team show up for each stat block even tho the data is still there.
Serializers can cut down on the clutter you will end up with in some of your controllers!