If you've already learned how to relate models in rails using macro associations like:
belong_to
has_many
or
has_many, through:
You may be wondering how these relationships manifest themselves when you actually pull data from your models. The answer is: they don't. That is, unless you use a serializer with your model.
A serializer is a separate file that kind of acts like a filter to its model. It determines what attributes from the model's records will be rendered or not rendered.
So, for example, we could have a model whose records have 100 attributes, but in a specific fetch request, we only want to render 3 of them. We would program that using a serializer.
To create a serializer file, use the command:
$ rails g serializer Model_name
By default, the serializer will be linked to the model that shares its name.
Once the serializer is created, enter the file Model_name_serializer.rb and add the macro associations you want to use when rendering data.
class ModelNameSerializer
has_many :other_models
end
Now, when you pull a record from "Model_Name," it will not only render that specific record, but also the nested records of "Other_model" that belong to it.
This can be useful if you want to use data from various related models in a single fetch statement.
Top comments (0)