Ade Anlika Damayanti
Ade Anlika Damayanti

Reputation: 31

Rails merge multiple json response

Can anyone help me with this problem?

So, here is the problem, I want to merge this query response:

 @energy = Alert.where(["alert_type = ?", "Energy"]).last.as_json

 @cost = Alert.where(["alert_type = ?", "Cost"]).last.as_json

Then I merge those object with:

@current_notif = @energy.merge(@cost)

But those just give me @cost object like this:

{
  "alert_type": "Cost",
  "value": 30000000,
  "status": "Cost exceeds limit",
  "created_at": "2017-06-03T15:31:21.156+07:00",
  "updated_at": "2017-06-03T15:31:21.156+07:00",
  "home_id": 2
}

Rather than a merged @energy + @cost like this:

    { {"alert_type": "Energy",
       "value": 384455.813978742,
       "status": "Energy too high",
       "created_at": "2017-05-31T11:31:12.907+07:00",
       "updated_at": "2017-05-31T11:31:12.907+07:00",
       "home_id": 2 },
     {
       "alert_type": "Cost",
       "value": 30000000,
       "status": "Cost exceeds limit",
       "created_at": "2017-06-03T15:31:21.156+07:00",
       "updated_at": "2017-06-03T15:31:21.156+07:00",
       "home_id": 2
     }
}

Upvotes: 1

Views: 1873

Answers (2)

Sebastián Palma
Sebastián Palma

Reputation: 33420

If you want you could "join" both values, and then over that use as_json:

[@energy, @cost].as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]

Or if you want you could use the IN expression, in order to deal with ActiveRecord instead having to customize the result this gives you:

Alert.where(alert_type: ['Energy', 'Cost']).as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]

Upvotes: 2

Josh Brody
Josh Brody

Reputation: 5363

This is happening because that's how merge works.

hash = {:name => "Ade", :gender => "Male"}.merge(:name => "Bob") 
puts hash # {:name=>"Bob", :gender=>"Male"}

Solution:

results = [ @energy, @cost ]
results.each do |result|
  puts result['alert_type'] # Energy, Cost 
end 

Upvotes: 1

Related Questions