[英]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. 我正在尝试使用从API检索的数据绘制一个简单的line_chart,但文档示例仅使用来自常规ActiveRecord模型的数据,而且我正在苦苦挣扎。 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. 我有一个对REST API的调用,我得到了一个有两个属性的对象(还有一些属性,但这两个是我现在感兴趣的那些),ORDER_CODE和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.
我只想显示一个line_chart,其中X轴为order_codes,Y轴为lead_times。
My controller code is like that, I use Dish to convert the hash from Json.parse into an object. 我的控制器代码是这样的,我使用Dish将散列从Json.parse转换为对象。 The API call is working and I'm using the data succesfully in my app.
API调用正在运行,我正在我的应用程序中成功使用数据。
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: 我从API获得的JSON如下所示:
[{"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. 我终于通过在变量提前期中包含的原始哈希数组上使用collect方法来实现它,如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. 只需将@data作为参数传递给line_chart,图表就会被相关地绘制出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.