Reputation: 335
I have an Object ChatMessage, and I need a JSON with its User. I am using:
chat_message.as_json(include: { author: { only: [:id, :phone_number,
:country_alpha_2]})
I want to add data to author, let's say hello: "world"
. How can I do this?
I tried something like:
.as_json(include: { author: { only: [:id, :phone_number,
:country_alpha_2], hello: 'world'}})
and
.as_json(include: { author: { only: [:id, :phone_number,
:country_alpha_2]}.merge(hello: 'world') })
Upvotes: 1
Views: 122
Reputation: 33420
You can always use Object#tap:
.as_json(include: { author: { only: [:id, :phone_number, :country_alpha_2] } })
.tap { |json| json['author']['hello'] = 'world' }
Upvotes: 2
Reputation: 5313
Unless you want to tinker with the final hash yourself, i.e.
json = chat_message.as_json(include: { author: { only: [:id, :phone_number, :country_alpha_2] }})
json["author"].merge!(hello: "world")
you might add a method to your User
model and use :methods
as described in as_json docs:
class User
def hello
"world"
end
end
chat_message.as_json(include: {
author: { only: [:id, :phone_number, :country_alpha_2], methods: :hello }
})
Upvotes: 0