Chris Valentine
Chris Valentine

Reputation: 1637

Changing JSON field names in Rails responses

I need to allow for customization of json output per account. One person may like the standard json response. Another may wish to have the exact same feed except they need the "name" field called "account_name" or something.

So with a standard user they may be happy with

@model.to_json(only: [:name, :title, :phone])

Another user may wish to see their json response as

@model.to_json(only: [:name (AS ACCOUNT_NAME) , :title, :phone])

I have found solutions that override the as_json/to_json in the model but those seem to be solutions that effect everyone. How can I change them just on a per access/per account basis?

Upvotes: 0

Views: 1651

Answers (1)

Zhiliang Xing
Zhiliang Xing

Reputation: 1057

I think in your case, it is better to push the logic to the view layer to make the code clean by using Jbuilder. so instead of override to_json method you can do something like below:

# app/views/users/show.json.jbuilder

json.model_name do
  json.title @current_user.title
  json.phone @current_user.phone
  if current_user.type_account_name?  # need to implement this logic somewhere in your app
    json.account_name @current_user.name
  else
    json.name @current_user.name
  end
end

update

the controller looks something like this

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
  end
end

Upvotes: 3

Related Questions