Fast JSON API
The Fast JSON API is a JSON serializer for Rails APIs. … The result is that in our controller actions, rather than writing a custom render each time, we write out a serializer for each object once and use Fast JSON API to control the way our data is structured.
To install JSON API add the gem to your gemfile
gem 'fast_jsonapi'
and run bundle in your terminal
$ bundle install
Now in your Rail application generalize new serializer that has same name as your controller. let say I have controller named Movie has name and year attributes.
rails g serializer Movie name year
This will create a new serializer in app/serializers/movie_serializer.rb
let say your movie model look like this:
class Movie
attr_accessor :id, :name, :year, :actor_ids, :owner_id, :movie_type_id
end
your serializer in app/serializers/movie_serializer.rb
class MovieSerializer
include FastJsonapi::ObjectSerializer
set_type :movie # optional
set_id :owner_id # optional
attributes :name, :year
has_many :actors
belongs_to :owner, record_type: :user
belongs_to :movie_type
end
create new movie object
movie = Movie.new
movie.id = 232
movie.name = 'test movie'
movie.actor_ids = [1, 2, 3]
movie.owner_id = 3
movie.movie_type_id = 1
this will return Serialized JSON that is nested hash:
json_string = MovieSerializer.new(movie).serialized_json
that look like this
{
"data": {
"id": "3",
"type": "movie",
"attributes": {
"name": "test movie",
"year": null
},
"relationships": {
"actors": {
"data": [
{
"id": "1",
"type": "actor"
},
{
"id": "2",
"type": "actor"
}
]
},
"owner": {
"data": {
"id": "3",
"type": "user"
}
}
}
}
}
Resources