JSON is favorite format for exchanging data between server and client developers. Rails provides support for rendering proper JSON response, making it easy to focus on core functionality of application. Here are few things I learned to create clean, customized response.
Suppose we have a User model with fields such as first_name, last_name, picture, age, authentication_token, password_digest and timestamps fields such as created_at and updated_at. Using render json: @user will convert user object to json by calling “to_json” method of user for you.
Generated response contains all fields of our User model, including authentication tokens, password digest, timestamps or other sensitive information related to user which should not be permitted in response.
To prevent such information from being sent I used to prepare customized json responses by logic related to rendering inside of helper classes and controller actions. That approach just increased redundancy, inconsistency, inefficiency and was harder to maintain. Luckily, soon I got introduced to concept of overriding “as_json” method.
This approach seems clean and nice. We are now showing only name, picture and age fields. But this is not enough.
Suppose, our user can have many emails. Now with user response, we need to send data about emails that a user owns. We don’t want to send timestamps fields of any models. Also, we want to send emails information in only certain requests where they are required. Such customization can be done by using options hash and passing which fields we want in our response.
In above example, by default when we call
It returns user hash with related emails information. Note that only required information is passed in response json. When we need to exclude emails information from response, we just need to pass fields we need in options hash as shown in example as:
This is the approach I use generally to simplify json response, and is very effective.
There is one better approach of using active model serializers which delegates as_json and to_json to adapters. I am learning how use that in my projects as I came to know about it recently. So far active model serializers seems cleaner and more flexible approach than overriding as_json method, and will post about that soon.
Thanks for reading, you can let me know about how you render json response and what you do to improve the process.