MobileOverlord
MobileOverlord

Reputation: 4610

ActiveRecord as_json return different column names

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.

Upvotes: 2

Views: 1084

Answers (2)

mu is too short
mu is too short

Reputation: 434705

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.

Upvotes: 2

Leventix
Leventix

Reputation: 3859

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

and define that method on record.

Upvotes: 1

Related Questions