如何将信息添加到Rails JSON对象?

时间:2018-11-25 15:54:31

标签: ruby-on-rails

我有一个对象ChatMessage,我需要一个带用户的JSON。我正在使用:

chat_message.as_json(include: { author: { only: [:id, :phone_number, 
:country_alpha_2]})

我想向作者添加数据,比方说hello: "world"。我该怎么办?

我尝试过类似的事情:

.as_json(include: { author: { only: [:id, :phone_number, 
:country_alpha_2], hello: 'world'}})

.as_json(include: { author: { only: [:id, :phone_number, 
:country_alpha_2]}.merge(hello: 'world') })

2 个答案:

答案 0 :(得分:1)

您始终可以使用Object#tap

.as_json(include: { author: { only: [:id, :phone_number, :country_alpha_2] } })
.tap { |json| json['author']['hello'] = 'world' }

答案 1 :(得分:0)

除非您想自己修改最终的哈希值,即

json = chat_message.as_json(include: { author: { only: [:id, :phone_number, :country_alpha_2] }})
json["author"].merge!(hello: "world")

您可以在User模型中添加方法,并按照as_json文档中的说明使用:methods

class User
  def hello
    "world"
  end
end

chat_message.as_json(include: {
  author: { only: [:id, :phone_number, :country_alpha_2], methods: :hello }
})