2

I am trying to return a JSON representation of an ActiveRecord but instead of having the JSON string contain the model's column names for the Keys I would like to have it display something different per column. Is there a way to do this? here is my example line

record.as_json(root: false, :only => [:message, :user])

I basically want it to return the message and the user columns, but I want to call them something else when it gets them.

2 Answers 2

2

I think you're overcomplicating this. You only want two columns so why not just do it by hand?

def some_controller
  #...
  json = {
    new_name_for_message: r.message,
    new_name_for_user:    r.user
  }
  render json: json, status: :ok
end

Build a two element Hash and hand it off to the JSON rendering system.

1
record.as_json(root: false, :only => [:user], :methods => [:message_html])

and define that method on record.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.