Serializing JSON Data in Rails
JSON data is a big part of creating an API and curating the data in a consistent way is essential to consuming that data. When creating a Ruby on Rails API we have a few different ways to deal with this but today I’m going to talk about Active Model Serializer. It provides easy convention for managing the structure of your JSON data.
to_json
Let’s create a scenario where we had a Rails blog application. If we wanted to view an instance of Post
we would also want to see the associated Author
of that post. We can use the Active Record method to_json
which allows us to include the necessary attributes of the Post
and it’s Author
. It would look like this:
# posts_controller.rbdef show
@post = Post.find(params[:id])
render json: @post.to_json(only: [:title, :description, :id],
include: [author: { only: [:name]}])end
You can see in this example that we are having the controller render the JSON data which includes an Active Record relationship between a Post
and Author
.
However, we can see from this example that curating JSON data in this manner will get ugly very quickly. If there were any further relationships we wanted to display or if the object we wanted to render included anymore attributes it…