Rails合并多个json响应

时间:2017-06-04 00:21:08

标签: ruby-on-rails json ruby hash merge

任何人都可以帮我解决这个问题吗?

所以,这是问题,我想合并这个查询响应:

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

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

然后我将这些对象合并为:

@current_notif = @energy.merge(@cost)

但那些只是给我@cost这样的对象:

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

而不是像这样合并@energy + @cost

    { {"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 个答案:

答案 0 :(得分:2)

如果你想要,你可以加入"两个值,然后使用as_json

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

或者如果你想要你可以使用IN表达式,为了处理ActiveRecord而不必自定义结果,这会给你:

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

答案 1 :(得分:1)

这种情况正在发生,因为这是合并的工作方式。

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

解决方案:

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