1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Serialize With fast_jsonapi In A Rails App as a rails til

This commit is contained in:
jbranchaud
2019-02-08 15:06:09 -06:00
parent 3e4188b3a1
commit a088cf14d7
2 changed files with 54 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/). [til.hashrocket.com](https://til.hashrocket.com/).
_761 TILs and counting..._ _762 TILs and counting..._
--- ---
@@ -485,6 +485,7 @@ _761 TILs and counting..._
- [Secure Passwords With Rails And Bcrypt](rails/secure-passwords-with-rails-and-bcrypt.md) - [Secure Passwords With Rails And Bcrypt](rails/secure-passwords-with-rails-and-bcrypt.md)
- [Select A Select By Selector](rails/select-a-select-by-selector.md) - [Select A Select By Selector](rails/select-a-select-by-selector.md)
- [Select Value For SQL Counts](rails/select-value-for-sql-counts.md) - [Select Value For SQL Counts](rails/select-value-for-sql-counts.md)
- [Serialize With fast_jsonapi In A Rails App](rails/serialize-with-fast-jsonapi-in-a-rails-app.md)
- [Set Schema Search Path](rails/set-schema-search-path.md) - [Set Schema Search Path](rails/set-schema-search-path.md)
- [Show Pending Migrations](rails/show-pending-migrations.md) - [Show Pending Migrations](rails/show-pending-migrations.md)
- [Show Rails Models With Pry](rails/show-rails-models-with-pry.md) - [Show Rails Models With Pry](rails/show-rails-models-with-pry.md)

View File

@@ -0,0 +1,52 @@
# Serialize With fast_jsonapi In A Rails App
Netflix put out a Ruby gem for super fast JSON serialization --
[`fast_jsonapi`](https://github.com/Netflix/fast_jsonapi). It is great for
serializing JSON responses for Rails API endpoints.
First, add `gem 'fast_jsonapi'` to your `Gemfile` and `bundle install`.
Then create the `app/serializers` directory for housing all of your JSON
serializers.
Next you can create a `serializer` that corresponds to the model you want to
serialize:
```ruby
# app/serializers/recipe_serializer.rb
class RecipeSerializer
include FastJsonapi::ObjectSerializer
set_id :id
attributes :name, :source_url
end
```
Last, use it to generate a JSON response in your controller:
```ruby
# app/controllers/recipes_controller.rb
class RecipesController < ApiController
def index
render json: RecipeSerializer.new(@current_user.recipes)
end
end
```
Requests to that endpoint will receive a response that looks something like
this:
```json
{
data: [
{
id: 1,
attributes: { name: "Old Fashioned", source_url: "http://..." },
},
{
id: 2,
attributes: { name: "Sazerac", source_url: "http://..." },
},
]
}
```