试图建立一个标准的股票图表,但没有乐趣发送数据到highcharts。尝试Chartkick没有任何乐趣,因为不需要分组或求和,只需要简单的日期和价格。问题是将数据发送到highcharts,似乎无法破解这一点。
Rails 4.5
gem 'highcharts-rails', '~> 4.2', '>= 4.2.5'应用程序js
//= require highcharts
//= require highcharts/highcharts-more在控制器操作中
def action
@rates_hash = @code.rates.each do |rate|
date = rate.day.strftime("%Y-%m-%d")
rates_hash[date] = rate.price.to_i
end在辅助对象中
def data_series(rates_hash)
dates = (rates_hash.keys.min..rates_hash.keys.max).to_a
dates.map do |date, value|
js_date = "Date.UTC(#{date.year}, #{date.month - 1}, #{date.day})"
"[#{js_date}, #{rates_hash[date].to_i}]"
end
end在我看来
<div id="graph" class="graph" data-rates="<%= @rates_array %>">
<script type="text/javascript">
const data = [<%= data_series(@rates_hash).join(",") %>];
Highcharts.stockChart('graph', {
title: {
text: 'USD-ZAR'
},
xAxis: {
type: 'datetime'
title: {
text: 'Date'
}
},
yAxis: {
crosshair: true
title: {
text: 'Pain level'
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.y}'
},
},
rangeSelector: {
selected: 1
},
series: [{
name: 'Rates',
data: data
}]
});模型是:费率
class CreateRates < ActiveRecord::Migration
def change
create_table :rates do |t|
t.date :day
t.references :code, index: true, foreign_key: true
t.decimal :price, :precision => 14, :scale => 6
end
end
end我得到的错误是:未定义的局部变量或方法`rates_hash‘帮助赞赏。谢谢--
发布于 2017-09-04 21:16:44
我设法使用了chartkick并在控制器中使用了一个私有方法。
private
def set_rates(code_id)
@rates.inject({}) do |new_element, current_element|
day = current_element.day
price = current_element.price
new_element[day] = price
new_element
end
end这很有效,只是我更喜欢使用普通的highcharts
https://stackoverflow.com/questions/45970277
复制相似问题