我有一个Ruby / Rails视图,其中员工姓名将显示在Y轴(左侧)和周日期从星期日开始到周末结束。
'2017-02-05' '2017-02-06' '2017-02-07' '2017-02-08' '2017-02-09' '2017-02-10' '2017-02-11'
Employee_1 7 3 4.5
Employee_2 4 6.2 0.5 10.5
当我从数据库中提取详细信息时,数据将采用以下格式。日期格式为YYYY-MM-DD
。
@data =
{"Employee_1"=>
[{"week_date"=>"2017-02-05",
"log_time"=>"7"},
{"week_date"=>"2017-02-08",
"log_time"=>"3"},
{"week_date"=>"2017-02-09",
"log_time"=>"4.5"}],
"Employee_2"=>
[{"week_date"=>"2017-02-06",
"log_time"=>"4"},
{"week_date"=>"2017-02-07",
"log_time"=>"6.2"},
{"week_date"=>"2017-02-08",
"log_time"=>"0.5"},
{"week_date"=>"2017-02-10",
"log_time"=>"10.5"}]
}
另外,我们有一个包含工作日的数组:
@week_days = ["2017-02-05", "2017-02-06", "2017-02-07", "2017-02-08", "2017-02-09", "2017-02-10", "2017-02-11"]
如何循环此结构并显示数据可用日期的数据,并在视图中的HTML表结构中跳过其余日期?
答案 0 :(得分:3)
让我们从准备步骤开始。我们需要stub
周工作日,我们稍后会将其用作原始数据的支架:
stub = @week_days.map { |wd| {wd => ""} }.reduce(&:merge)
和原始数据的缩减器:
reducer = ->(v) {
v.map { |h| {h["week_date"] => h["log_time"]} }.reduce(&:merge)
}
好的,我们都准备好了。
@data.map { |k, v| [k, stub.merge(reducer.(v))] }.to_h
#⇒ {
# "Employee_1" => {
# "2017-02-05" => "7",
# "2017-02-06" => "",
# "2017-02-07" => "",
# "2017-02-08" => "3",
# "2017-02-09" => "4.5",
# "2017-02-10" => "",
# "2017-02-11" => ""
# },
# "Employee_2" => {
# "2017-02-05" => "",
# "2017-02-06" => "4",
# "2017-02-07" => "6.2",
# "2017-02-08" => "0.5",
# "2017-02-09" => "",
# "2017-02-10" => "10.5",
# "2017-02-11" => ""
# }
# }
现在只需重复上述操作并打印值。