Kilmer Luiz Aleluia
Kilmer Luiz Aleluia

Reputation: 335

How to add info to rails JSON object?

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

Answers (2)

Sebastián Palma
Sebastián Palma

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

Marcin Kołodziej
Marcin Kołodziej

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

Related Questions