我正在执行一个查询,并以数组(MySql2类型对象)的形式从数据库中获取以下数据:
+-----------+---------------+---------------+------+------+---------------+
| build | platform_type | category_name | pass | fail | indeterminate |
+-----------+---------------+---------------+------+------+---------------+
| 10.0.1.50 | 8k | UMTS | 10 | 2 | 5 |
| 10.0.1.50 | 8k | UMTS | 10 | 2 | 5 |
| 10.0.1.50 | 8k | IP | 10 | 2 | 5 |
| 10.0.1.50 | 8k | IP | 14 | 1 | 3 |
| 10.0.1.50 | 9k | IP | 14 | 1 | 3 |
| 10.0.1.50 | 9k | IP | 12 | 1 | 1 |
| 10.0.1.50 | 9k | UMTS | 12 | 1 | 1 |
| 10.0.1.50 | 9k | UMTS | 12 | 1 | 1 |
| 10.0.1.50 | 9k | UMTS | 12 | 1 | 1 |
| 10.0.1.50 | 9k | Stability | 9 | 4 | 0 |
| 10.0.1.50 | 9k | Stability | 15 | 1 | 0 | 我想将它显示在我的UI中的一个表中,如下所示:
+-----------+---------------+---------------+------+------+---------------+
| build | platform_type | category_name | pass | fail | indeterminate |
+-----------+---------------+---------------+------+------+---------------+
| | | UMTS | 20 | 4 | 10 |
| | 8k |---------------------------------------------|
| | | IP | 24 | 3 | 8 |
| |---------------|---------------------------------------------|
| 10.0.1.50 | | IP | 26 | 2 | 4 |
| | |---------------------------------------------|
| | 9k | UMTS | 36 | 3 | 3 |
| | |---------------------------------------------|
| | | Stability | 24 | 5 | 0 |
---------------------------------------------------------------------------我确实尝试过使用hash来为构建找到唯一的平台类型。但由于我是ruby的新手,我在正确使用散列时遇到了问题。如果有人能帮我解析一下这些数据,我将不胜感激。
发布于 2013-04-25 06:55:13
假设您有一个数组数组:
@data = sql_results.group_by(&:first).map do |b, bl|
[b, bl.group_by(&:second).map{|p, pl| [p, pl.map{|r| r[2..-1]}] }.sort_by(&:first)]
end.sort_by(&:first)以下是如何分解逻辑的方法。
对生成列表进行排序
生成的结构如下所示:
[
[
"10.0.1.50", [
[
"8k", [
["UMTS", 20, 4, 10],
["IP", 24, 3, 8]
]
],
[
"9k", [
["IP", 26, 2, 4],
["UMTS", 36, 3, 3],
["UMTS", 24, 5, 0]
]
]
]
]
]您可以在视图布局示例中使用以下内容:
%table
%tr
- %w(build platform_type category_name pass fail indeterminate).each do |name|
%th=name
- @data.each do |build, build_list|
%tr
%td=build
%td{:colspan=4}
%table
- build_list.each do |build, platform_list|
%tr
%td=build
%td{:colspan=3}
%table
- platform_list.each do |row|
%tr
- row.each do |attr|
%td=attr如果您使用AR模型,请执行以下操作:
class Build < ActiveRecord::Base
def self.builds_by_platform
reply = Hash.new{|h, k| h[k] = Hash.new{|h, k| h[k] = []}}
Build.order("build ASC, platform_type ASC").find_each do |row|
reply[row.build][row.platform_type] << row
end
reply.map{|b, bh| [b, bh.sort_by(&:first)}.sort_by(&:first)
end
end在您的控制器中,您可以访问规范化变量,如下所示:
@report _list = Build.builds_by_platform您可以使用@report _list变量来呈现表格。
https://stackoverflow.com/questions/16203057
复制相似问题