You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+54Lines changed: 54 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -453,3 +453,57 @@ export default Button;
453
453
This should be everything we need to setup the API. Simply click our test api call button and see the magic work!
454
454
455
455
### 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.
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 classon 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!
0 commit comments