Using Chartkick in Rails 4.0

2019-02-04 17:29发布

问题:

How can i use Chartkick in rails 4.0.

in Gem I added:

gem "chartkick"

and in my view for example i added this:

<%= pie_chart({"Football" => 10, "Basketball" => 5}) %>

but the page only show Loading... generated Html:

<div id="chart-1" style="height: 300px; text-align: center; color:
#999; line-height: 300px; font-size: 14px; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif;">   Loading... </div> <script type="text/javascript">   new Chartkick.PieChart("chart-1", {"Football":10,"Basketball":5}, {}); </script>

回答1:

Be sure to include the JavaScript files before the charts.

<%= javascript_include_tag "//www.google.com/jsapi", "chartkick" %>


回答2:

To get chartkick working in Rails 4, I did the following:

1. Added chartkick gem to my Gemfile (bundle install)

gem 'chartkick'

2. Downloaded Google jsapi file into my vendor directory

/railsapp/vendor/assets/javascripts/jsapi.js

3. Added chartkick and jsapi to my application.js

//= require jsapi
//= require chartkick

After that, charts showed up on a consistent basis.



回答3:

Loading your charts superfast

i am using highcharts here as it do not require you to connect each time to google server

add this gem

gem "chartkick"

then download highchart.js from here http://www.highcharts.com/download

paste the file in your app/vendor/assets/javascript/highchart.js

open your application.js and require these two files

//= require highcharts.js
//= require chartkick

after this you are good to go and your charts will load within a blink



回答4:

There are actually 2 ways to solve this, refer to the "Installation" guidelines: http://ankane.github.io/chartkick/

For Google Charts, use:

<%= javascript_include_tag "//www.google.com/jsapi", "chartkick" %>

If you prefer Highcharts, use:

<%= javascript_include_tag "path/to/highcharts.js", "chartkick" %>

For those who are thinking of using jsapi offline, you cant really, even if you have downloaded jsapi.js, it still does a further load to google. You are just breaking the terms:

Extract from: Google Charts FAQ

Can I use charts offline?

No; your computer must have live access to http://www.google.com/jsapi in order to use charts. This is because the visualization libraries that your page requires are loaded dynamically before you use them. The code for loading the appropriate library is part of the included jsapi script, and is called when you invoke the google.load() method. Our terms of service do not allow you to download the google.load or google.visualization code to use offline.

Can I download and host the chart code locally, or on an intranet?

Sorry; our terms of service do not allow you to download and save or host the google.load or google.visualization code.