Create a Chart Using Ruby on Rails
Overview
FusionCharts Suite XT includes the FusionCharts server-side RoR wrapper that lets you create interactive, data-driven charts. Using the wrapper, you can create charts in your browsers without writing any JavaScript code. The required JavaScript and HTML code is generated as a string in the server and inserted in the web page to generate charts.
In this article, we will show you how to install and render a chart using the FusionCharts Rails gem wrapper.
Installation
In this article, we will show you how to download and install the FusionCharts Rails gem wrapper and all the other dependencies on your system.
Copy the
fusionCharts-rails.rbfromintegrations > rubyonrails > fusioncharts-wrapperin your project folder.Include the FusionCharts JavaScript files, which can be downloaded from here.
Include the FusionCharts theme file to apply the style to the charts.
// Include FusionCharts core file
<script type="text/javascript" src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
// Include FusionCharts Theme file
<script type="text/javascript" src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
// Include FusionCharts core file
<script type="text/javascript" src="path/to/local/fusioncharts.js"></script>
// Include FusionCharts Theme file
<script type="text/javascript" src="path/to/local/themes/fusioncharts.theme.fusion.js"></script>
- Add the FusionCharts Rail wrapper:
- Using RubyGems
 - Manually
 
 - Include the FusionCharts Rails wrapper.
 
To add the FusionCharts Rails wrapper, use any of the following processes:
Gemfile:
    gem ‘fusioncharts-rails’
    $bundle
fusioncharts-rails gem. You can also install the gem directly from the command line prompt, without making any edits to the Gemfile. To do this, use the code line given below:
    $gem install fusioncharts-rails
fusioncharts-suite-xt > integrations > rubyonrails > fusioncharts-wrapper folder.lib folder of your applicationThat completes the installation of FusionCharts Suite and the Rails wrapper.
Create Your First Chart
Let's start with a simple example of "Countries With Most Oil Reserves" chart, which we will plot in a Column 2D chart as shown below:
FusionCharts Suite has 95+ chart types for you to explore. Find the complete list of chart types here .
To understand the chart components, click here.
Chart data
The data to render the above chart is shown in the table below:
| Country | No. of Oil Reserves | 
|---|---|
| Venezuela | 290K | 
| Saudi | 260K | 
| Canada | 180K | 
| Iran | 140K | 
| Russia | 115K | 
| UAE | 100K | 
| US | 30K | 
| China | 30K | 
FusionCharts accepts data in JSON format. Following code is the JSON representation of the above table with the required attributes to render the above chart.
{
    // Chart Configuration
    "chart": {
        "caption": "Countries With Most Oil Reserves [2017-18]",
        "subCaption": "In MMbbl = One Million barrels",
        "xAxisName": "Country",
        "yAxisName": "Reserves (MMbbl)",
        "numberSuffix": "K",
        "theme": "fusion",
    },
    // Chart Data
    "data": [{
        "label": "Venezuela",
        "value": "290"
    }, {
        "label": "Saudi",
        "value": "260"
    }, {
        "label": "Canada",
        "value": "180"
    }, {
        "label": "Iran",
        "value": "140"
    }, {
        "label": "Russia",
        "value": "115"
    }, {
        "label": "UAE",
        "value": "100"
    }, {
        "label": "US",
        "value": "30"
    }, {
        "label": "China",
        "value": "30"
    }]
}
Different types of charts in FusionCharts expect different JSON formats, based on their grouping. Explore different JSON formats, for example, single-series,multi-series, combination charts.
In the above JSON data:
Create the
chartobject to define the elements of the chart.Set the
captionandsubcaptionof the chart.Set the value of
xAxisNameattribute to Country(first column of the table).Set the value of
yAxisNameattribute to Reserves(second column of the table).In the
dataarray, create objects for each row and specify thelabelattribute to represent the Country. For example, Venezuela.Similarly, specify the
valueattribute to set the value of Oil Reserves in respective countries. For example, 290K for Venezuela.Set the
numberSuffixattribute to set the unit of the values.Set the
themeattribute to apply the predefines themes to the chart.
Both the chart object and the data array contain a set of key-value pairs known as attributes. These attributes are used to set the functional and cosmetic properties of the chart.
Now that you have the data in JSON format, let's see how to render the chart.
Render the Chart
To render the chart, follow the steps below:
Include the FusionCharts Rails wrapper in your project.
Include the
fusionchartslibrary.Include the FusionCharts theme file to apply the style to the charts.
Set the chart appearance configuration to display the data in the chart.
Create an array named
chartDataObjof hash objects which stores data.Create a chart data template to store data in
labelandvalue.Set te chart data as JSON string.
Create the chart instance and set the following:
Set the chart type as
column2d. Each chart type is represented with a unique chart alias. For Column 2D chart, the alias iscolumn2d. Find the complete list of chart types with their respective alias here.Set the
widthandheight(in pixels).Set the container for the chart.
Set the
dataFormatas JSON.Embed the
jsondata as the value of thedataSource.
Create a container using
<div>to render the chart.
The full code for the above sample is:
require 'json'
require 'fusioncharts-rails'
class FirstChart
    def self.getChart
        # Chart appearance configuration
        chartAppearancesConfigObj = Hash.new
        chartAppearancesConfigObj = { 
                        "caption" => "Countries With Most Oil Reserves [2017-18]",
                        "subCaption" => "In MMbbl = One Million barrels", 
                        "xAxisName" => "Country",
                        "yAxisName" => "Reserves (MMbbl)", 
                        "numberSuffix" => "K", 
                        "theme" => "fusion"
                    }
        # An array of hash objects which stores data
        chartDataObj = [
                    {"Venezuela" => "290"},
                    {"Saudi" => "260"},
                    {"Canada" => "180"},
                    {"Iran" => "140"},
                    {"Russia" => "115"},
                    {"UAE" => "100"},
                    {"US" => "30"},
                    {"China" => "30"}
                ]
        # Chart data template to store data in "Label" & "Value" format
        labelValueTemplate = "{ \"label\": \"%s\", \"value\": \"%s\" },"
        # Chart data as JSON string
        labelValueJSONStr = ""
        chartDataObj.each {|item| 
            data = labelValueTemplate % [item.keys[0], item[item.keys[0]]]
            labelValueJSONStr.concat(data)
        }
        # Removing trailing comma character
        labelValueJSONStr = labelValueJSONStr.chop
        # Chart JSON data template
        chartJSONDataTemplate = "{ \"chart\": %s, \"data\": [%s] }"
        # Final Chart JSON data from template
        chartJSONDataStr = chartJSONDataTemplate % [chartAppearancesConfigObj.to_json, labelValueJSONStr]
        # Chart rendering 
        chart = Fusioncharts::Chart.new({
                width: "700",
                height: "400",
                type: "column2d",
                renderAt: "chartContainer",
                dataSource: chartJSONDataStr
            })
    end
end
The HTML template of the above sample is shown below:
<!-- Filename: app/views/examples/firstchart.html.erb -->
<h3>My Chart</h3>
<div id="chart-container"></div>
<%[email protected]() %>
That's it! Your first chart using FusionCharts Rails wrapper is ready. When you run this HTML page now, you should see a chart representing your data.
Problem rendering the chart?
In case there is an error, and you are unable to see the chart, check for the following:
If you are getting a JavaScript error on your page, check your browser console for the exact error and fix accordingly. If you're unable to solve it, click here to get in touch with our support team.
If the chart does not show up at all, but there are no JavaScript errors, check if the FusionCharts Suite XT JavaScript library has loaded correctly. You can use developer tools within your browser to see if
fusioncharts.jswas loaded.If you get a Loading Data or Error in loading data message, check whether your JSON data structure is correct, or there are conflicts related to quotation marks in your code.