0

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?

4
  • 1
    There is no "Rails way" to do this, because it's an extremely weird thing to want to do. How do you intend to store the custom field names? It's up to you to take that custom field mapping and apply it to the output of as_json in whatever front-end handles the request. Commented Apr 12, 2016 at 20:59
  • field aliases would be stored in a template of some kind, or just a remap "set name = new_name" or something similar. Some Users backends require different input so i'm forced to accomodate Commented Apr 12, 2016 at 21:07
  • @7urkm3n That's not remotely valid syntax, but to be fair, the samples in the question aren't valid syntax either. Commented Apr 12, 2016 at 21:11
  • updated post to have better syntax (i think, i'm new) Commented Apr 12, 2016 at 21:17

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I can work with this. What does the controller look like for this?
Jbuilder is part of rails, so if you don't want to return html version, but just json version, you actually can just simply remove @model.to_json(only: [:name, :title, :phone]), just make sure @model is assigned. then rails will automatically render the jbuilder template for you
If you find it works later, please accept my solution. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.