csakon
csakon

Reputation: 611

How to add data to returned ActiveRecord query records

I'm doing a simple query to a database table to send off to an external service, but I need to add an element to each of the returned records before I do so.

app.rb

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

  @contacts.to_json
end

Provides me the data I need formatted as

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

But I need to add the provided task within the route to the results before sending it off via json as such:

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

How do I iterate over the returned results before sending it off?

Upvotes: 0

Views: 52

Answers (1)

Ursus
Ursus

Reputation: 30056

Try this one. map method to transform your result, attributes method to have an hash with fields and values and merge method to add the task.

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

Upvotes: 2

Related Questions