Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何向返回的ActiveRecord查询记录添加数据_Arrays_Ruby_Activerecord_Sinatra - Fatal编程技术网

Arrays 如何向返回的ActiveRecord查询记录添加数据

Arrays 如何向返回的ActiveRecord查询记录添加数据,arrays,ruby,activerecord,sinatra,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":"a014100000AYi

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

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"}]

如何在发送返回的结果之前对其进行迭代?

试试这个
map
method转换结果,
attributes
method使用字段和值进行哈希,以及
merge
method添加任务

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

试试这个
map
method转换结果,
attributes
method使用字段和值进行哈希,以及
merge
method添加任务

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