1

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
     }
}
2
  • According to your example you want to receive an array, rather than a hash. Commented Jun 4, 2017 at 0:33
  • .merge is behaving the way it is supposed to. Read the docs: docs.ruby-lang.org/en/2.0.0/Hash.html#method-i-merge. Also, that resulting hash isn't a valid hash. Are you sure you don't want an array? Commented Jun 4, 2017 at 0:34

2 Answers 2

2

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", ... }]
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.