简体   繁体   中英

Chartkick/Rails: Build line_chart using data from an object instead of a Model

I'm trying to draw a simple line_chart using data retrieved from an API, but the documentation examples only use data from regular ActiveRecord Model and I'm struggling a lot. Since I'm not operating over a Model I can't use any of the methods explained in the docs (group etc)

I have this call to a REST API, I got an object with two attributes (there are a few more, but these two are the ones I'm interested at this point), ORDER_CODE and LEAD_TIME. I just want to display a line_chart with the order_codes in the X axis and the lead_times in the Y axis.

My controller code is like that, I use Dish to convert the hash from Json.parse into an object. The API call is working and I'm using the data succesfully in my app.

leadtimes = Dish(JSON.parse RestClient.get(ENV['API'], params: { PART: @order.PART }))

And in the view:

<%= line_chart @data%> 

I was trying this, but I just got an empty chart:

@data = leadtimes.map do |value|
  [
    order_code: value.ORDER_CODE, lead_time: value.LEAD_TIME
  ]
end

The JSON I got from the API looks like this:

[{"ORDER_CODE"=>519805, "PART"=>"00049", "LEAD_TIME"=>29, "DATE"=>"2015-03-03T00:00:00"}, {"ORDER_CODE"=>517297, "PART"=>"00149", "LEAD_TIME"=>54, "DATE"=>"2014-11-26T00:00:00"}]

I finally got it working by using the collect method over the original array of hashes contained in the variable leadtimes as shown in the OP.

@data = leadtimes.collect{|i| [i['ORDER_CODE'], i['lead_time']]}

Just passing @data as an argument to line_chart the chart gets drawn correectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM