When we call as_json on ActiveRecord model object, it returns json of attributes on model by calling as_json. We can override as_json method and add extra attributes, rename keys, add values of methods on object to the json returned.
Let’s take an example to understand this.
Let’s say we have a model
Post as given below.
The post has values as given below.
Now, calling as_json returns hash as given below.
Let’s look at the source code of
This method works as given below.
- It checks, if
optionspassed has key
rootkey is passed or
ActiveRecord::Base.include_root_in_json = trueis set to
true, it will include root node (model name) in resultant hash / json.
- At the end it calls
serializable_hashwith options that uses ActiveModel::Serializer to serialize the model attributes.
Override as_json method on ActiveRecord model object
Let’s say, we want to add
user_name as well in the response
user_id of the
We can achive this by overriding
as_json key in the response.
- Here, we have overriden
super(options)to fetch json that would have been returned otherwise.
user_namekey-value in the resultant hash / json.
Rename key on as_json response of ActiveRecord model object
Similarly, we can rename key from the response of
as_json, by overriding the method.
Here, we have renamed the
title key in the resultant response
When json generation gets complicate with overriding
on ActiveRecord model object,
it is better to use jbuilder to generate json response for APIs
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox