Search code examples
ruby-on-railsrubyruby-on-rails-4sequelchartkick

Chartkick, line_chart (not series) data with hash in array


I have the following query which is a raw SQL using Sequel's .fetch method (Hopefully i can use the sequel DSL for this)

Radacct.fetch("SELECT `acctstarttime` AS `date`, count(*) AS `count` FROM `radacct` WHERE (`calledstationid` = ?) GROUP BY DATE(acctstarttime)", 'C8-60-00-95-4B-0F')

The result data is:

[{"date":"2015-11-08T19:59:57.000+08:00","count":4},{"date":"2015-11-09T00:02:37.000+08:00","count":3}]

Which is hash in array. What chartkick gem's line_chart reads the data should be like this:

{"2015-12-09T03:31:25.000+08:00":1}

I am unsure how to use the .map function or .collect to flatten and remove the keys (date and count) so i can render the line chart in chartkick properly.


Solution

  • You need to put something like this :

    array.collect{|i| [i[:date],i[:count]]}
    

    And you get this:

    array= [{"date":"2015-11-08T19:59:57.000+08:00","count":4},{"date":"2015-11-09T00:02:37.000+08:00","count":3}]
    => [{:date=>"2015-11-08T19:59:57.000+08:00", :count=>4}, {:date=>"2015-11-09T00:02:37.000+08:00", :count=>3}]
    array.collect{|i| [i[:date],i[:count]]}
    => [["2015-11-08T19:59:57.000+08:00", 4], ["2015-11-09T00:02:37.000+08:00", 3]]