Skip to content

Commit 3720056

Browse files
authored
Update README.md
1 parent 3a1c59e commit 3720056

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,3 +453,57 @@ export default Button;
453453
This should be everything we need to setup the API. Simply click our test api call button and see the magic work!
454454

455455
### Congratulations! Our Rails API and React Client is done!
456+
457+
458+
# Rails Serializers
459+
460+
What are Serializers? Well Rails API's returns JSON data in full, so serializers allows us to cherry pick the exact data we want in a much organized fashion. Instead of getting every column from the returned data, we can grab which ever we allow to pass through.
461+
462+
| Normal Model | Serializer Model |
463+
| ------------- |:-------------:|
464+
| id, name, rating, director, score, actors_id, created_at, updated_at| id, name, rating|
465+
466+
We are able to tell the Rails API what to fetch rather than the frontend; making it much more simple and faster to scaffold your next project.
467+
468+
1. Installation
469+
470+
Open your ```gemfile``` and add the serializer gem into your project. Don't forget to ```bundle install``` !
471+
```ruby
472+
# Serializer
473+
gem 'active_model_serializers'
474+
```
475+
476+
We want to create a clone of any current model we have so when we make requests in the backend, the request will read the serializer file <strong>first</strong>, then it will find the rails model/controller to finisht the request. We have a model called Movie so we'll duplicate that by running:
477+
478+
```
479+
rails g serializer movie
480+
```
481+
You can see that a new directory was made in the ```app/``` directory and we now have ```app/serializers/movie_serializer``` file in our project.
482+
483+
Let's open that file and see what we have:
484+
```ruby
485+
class MovieSerializer < ActiveModel::Serializer
486+
attributes :id
487+
end
488+
489+
```
490+
491+
We have our Movie Class inheriting from the serializer class on the first line, and the returned attribute on the second. So far the default returned attribute is just an ID. Let's test this now!
492+
493+
1a. Turn on your rails server and go to the url ``` localhost:3000/api/v1/movies ```
494+
495+
You should see that only the ```id``` attribute is being returned from the database.
496+
```json
497+
{
498+
id: 1
499+
},
500+
{
501+
id: 2
502+
},
503+
{
504+
id: 3
505+
}
506+
```
507+
508+
You can add any attribute to your liking to the serializer file for your next big project. But that's the end of the serializer section!
509+

0 commit comments

Comments
 (0)