首页 文章

Rails和highcharts(数据到highcharts)

提问于
浏览
0

试图 Build 一个标准的股票图表,但没有喜欢将数据发送到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'帮助赞赏 . 谢谢

1 回答

  • 0

    我设法使用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
    

    这很好用,而不是喜欢使用普通的高级图表

相关问题