如何将数据添加到返回的ActiveRecord查询记录中

时间:2017-04-18 23:17:21

标签: arrays ruby activerecord sinatra

我正在对数据库表进行简单查询以发送到外部服务,但在此之前我需要为每个返回的记录添加一个元素。

app.rb

get "/:task/:account_id/contacts" do
  @contacts = Contact.where("Account = ?", params[:account_id])

  @contacts.to_json
end

为我提供格式为

的数据
[{"Name":"Charlie Spencer","sfid":"a014100000AYi2ZABG","id":29,"Account":"a054100000FsEA8AAN"},{"Name":"Philip Leak","sfid":"a014100000AYi3PCHZ","id":48,"Account":"a054100000FsEA8AAN"}]

但我需要在路由中添加提供的任务,然后通过json将其发送出去:

[{"Name":"Charlie Spencer","sfid":"a014100000AYi2ZABG","id":29,"Account":"a054100000FsEA8AAN","Task":"a014100000AYiWMCC1"},{"Name":"Philip Leak","sfid":"a014100000AYi3PCHZ","id":48,"Account":"a054100000FsEA8AAN","Task":"a014100000AYiWMCC1"}]

如何在发送之前迭代返回的结果?

1 个答案:

答案 0 :(得分:2)

试试这个。 map方法转换结果,attributes方法包含字段和值的哈希值,merge方法添加任务。

get "/:task/:account_id/contacts" do
  @contacts = Contact.where("Account = ?", params[:account_id]).map do |c|
    c.attributes.merge("Task": params[:task])
  end

  @contacts.to_json
end