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.