【发布时间】:2021-12-22 08:50:47
【问题描述】:
我有两个查询正在运行和迭代,我的最终哈希如下所示。但是,我想对数据如何存储在我正在创建的散列中或在我完成创建后格式化它进行格式化。但我不确定如何实现所需的格式,其中names 属于相同的id,如下所示
示例数据的所需格式:
[
{
id: 1,
accepted: false,
trans: 10234
names: [
{ name: "Joe", amount: "$1,698.00" },
{ name: "Smith", amount: "$674.24" },
]
},
{
id: 2,
accepted: true,
trans: 10234,
names: [
{ name: "Joe", amount: "$1,698.00" },
{ name: "Smith", amount: "$674.24" },
]
}
]
我目前的格式
[
{
:id => 1,
:accepted => false,
:trans => 8,
:name => "Smith",
:amount => 36.0
},
{
:id => 1,
:amount => false,
:trans => 8,
:name => "Joe",
:amount => 6.0
},
{
:id => 3,
:accepted => false,
:trans => 8,
:name => "Tom",
:amount => 34.0
},
{
:id => 3,
:accepted => false,
:trans=> 8,
:name => "Martha",
:amount => 4.0
}
],
[
{
:id => 2,
:accepted => true,
:trans => 7,
:name => "Bob",
:amount => 35.0
},
{
:id => 2,
:accepted => true,
:trans => 7,
:name => "John",
:amount => 5.0
}
]
创建哈希的逻辑
imports = ListImports.limit(20).order(created_at: :DESC)
groups = imports.map{|import| ListImportGroup.where(list_import_id: import.id)}
pub_hash_true = []
pub_hash_false = []
hash = []
imports.map do |import|
hash << {
id: import.id,
trans: import.trans,
accepted: import.amount
}
end
hash.each do |import|
groups.flatten.each do |group|
accepted = import[:accepted]
num_transactions = import[:trans]
if accepted == false
pub_hash_false << {id: import[:id], accepted: accepted, trans: num_transactions, name: group.name, amount: group.amount}
else
pub_hash_true << {id: import[:id], accepted: accepted, trans: num_transactions, name: group.name, amount: group.amount}
end
end
end
【问题讨论】:
-
你是如何生成最终结果的?改变世代可能比事后重新格式化更有意义
-
@SaraFuerst 我正在迭代两组数据并以这种方式创建哈希。我更新了我的问题以包含逻辑
-
什么是
groups?您没有显示变量的来源。 -
为什么需要
pub_hash_true和pub_hash_false?您的问题最初不是关于将数据分成“真/假”组,并且您没有显示是否/如何使用这些变量。 -
@TomLord 它在被控制器调用时作为一个哈希返回。我更新了我的问题,以显示组的来源。这是结果查询。
pub_hash_true和 ``` pub_hash_false``` 是分开接受的:真/假值
标签: ruby-on-rails ruby hash