I would like to use Google visualization charts for displaying information into a graph.
The javascript function for setting value into the graph looks like this:
function drawLineChart(chartType) {
if(chartType == undefined) {
chartType = 'data1';
}
var data = {
data1: [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]
};
...
}
My problem is, that I don't know how to fill out array like this with values from database - any tip?
Thanks a lot
You will need to embed the javascript in erb. If you name your file chart.js.erb
, you will then be able to access Model
logic from the javascript through erb. The downside to this method is that the javascript will have to be compiled on every page view, rather then being a statically compiled asset. This can slow down page load time, and an alternative route should be sought if this will be a heavily trafficked page.
Example
chart.js.erb
function drawLineChart(chartType) {
if(chartType == undefined) {
chartType = 'data1';
}
var data = {
data1: [
<%= Model.all.map { |m| [m.year, m.sales, m.expenses] }.unshift(['Year', 'Sales', 'Expenses']) %>
]
};
...
}
Alternatively, you could create an AJAX request that populates the array on page load through an API controller. This method would allow the asset to be statically compiled, but is a bit more complex.
You can use 'data' attribute:
# statistics.js.coffee
jQuery ->
data = {
labels : $("#orders_chart").data('dates'),
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : $("#orders_chart").data('orders')
}
]
}
ordersChart = new Chart($("#orders_chart").get(0).getContext("2d")).Line(data)
#statistics/index.html.erb
<%= content_tag 'canvas', '', id: 'orders_chart', width: '1000', height: '600', data: {orders: (Order.week_ago.map &:total), dates: (Order.week_ago.map &:created_at)} %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With