gpt4 book ai didi

ruby-on-rails - Rails 合并多个 json 响应

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:25 25 4
gpt4 key购买 nike

谁能帮我解决这个问题?

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

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

最佳答案

如果你愿意,你可以“加入”这两个值,然后在上面使用 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", ... }]

关于ruby-on-rails - Rails 合并多个 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com