2017-06-04 40 views
1

任何人都可以幫助我解決這個問題嗎?Rails合併多個JSON響應

所以,現在的問題是,我想合併這個查詢響應:

@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像th是:

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

根據你的例子你想接收一個數組,而不是一個散列。 – yzalavin

+0

'.merge'表現出應有的樣子。閱讀文檔:https://docs.ruby-lang.org/en/2.0.0/Hash.html#method-i-merge。此外,生成的散列不是有效的散列。你確定你不想要一個'數組'嗎? – jvillian

回答

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 
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

Upvoted for the second answer。 –