将活动记录数据转换为JS图表结构的优雅方式

时间:2015-07-04 16:17:03

标签: ruby-on-rails ruby

我认为将数据库数据转换为图表结构,

对于红宝石来说,这是一个非常痛苦的工作。

举个例子,

我想显示折线图。

X轴(时间:月),Y轴(值)

我需要union数据集中的月份

然后从每个数据集中提取值

如果相应月份有no data

您需要填充零或任何其他值,您不能将其保留为空。否则图表将被移动。

我想知道是否有任何优雅的方法来解决我的问题。

因为要生成图表。对我来说,这是一项艰苦而冗长的工作。感谢

数据集1(从活动记录中获取)

Month: January, value: 65
Month: February, value: 59
Month: April, value: 81

数据集2(从活动记录中获取)

Month: January, value: 28
Month: March, value: 40

js图表的数据结构

    labels: ["January", "February", "March", "April"],
    datasets: [
        {
            data: [65, 59, 0, 81]
        },
        {
            data: [28, 0, 40, 0]
        }
    ]

1 个答案:

答案 0 :(得分:0)

考虑哈希和数组,并熟悉Array#map等方法。

irb(main):002:0> d1 = [["January", 65], ["February", 59], ["April", 81]];
irb(main):003:0* d2 = [["January", 28], ["March", 40]];

irb(main):007:0> h1 = Hash[d1]
=> {"January"=>65, "February"=>59, "April"=>81}
irb(main):008:0> h2 = Hash[d2]
=> {"January"=>28, "March"=>40}

irb(main):009:0> months = ["January", "February", "March", "April"]
=> ["January", "February", "March", "April"]

irb(main):010:0> months.map{ |month| h1[month] }
=> [65, 59, nil, 81]
irb(main):011:0> months.map{ |month| h1[month] || 0 }
=> [65, 59, 0, 81]

irb(main):012:0> [h1,h2].map{ |dataset| months.map{ |month| dataset[month] || 0 } }
=> [[65, 59, 0, 81], [28, 0, 40, 0]]
irb(main):015:0> [h1,h2].map{ |ds| {data: months.map{ |month| ds[month] || 0 }} }
=> [{:data=>[65, 59, 0, 81]}, {:data=>[28, 0, 40, 0]}]

irb(main):017:0> dsets = [h1,h2].map{ |ds| {data: months.map{ |month| ds[month] || 0 }} }
=> [{:data=>[65, 59, 0, 81]}, {:data=>[28, 0, 40, 0]}]
irb(main):018:0> {labels: months, dataset: dsets}
=> {:labels=>["January", "February", "March", "April"], :dataset=>[{:data=>[65, 59, 0, 81]}, {:data=>[28, 0, 40, 0]}]}