Rails 2.35 / Ruby 1.87
I’ve been trying jqplot.
With Fusion Charts, I was always using the builder files which rendered XML for the view . With jqPlot, if I can simply build a data string and insert it into the JavaScript that generates the graph, is there any reason to render JSON files (etc)?
Also, I couldn’t find any jqPlot Rails examples and just made something up. I was curious how what I did could have been written better (or if I did ok here).
Thanks!
CONTROLLER
---------------------
def provisioned_accounts
sql = %Q{
SELECT day_of, provisioned_accounts from daily_provisioned_accounts_rollup
}
graph_data = DailyProvisionedAccountsRollup.find_by_sql(sql)
@graph_data = ''
x = 0
graph_data.each do |g|
x += 1
if x == 1
@graph_data += "['" + g.day_of.to_s + "', " + g.provisioned_accounts.to_s + "]"
else
@graph_data += ", ['" + g.day_of.to_s + "', " + g.provisioned_accounts.to_s + "]"
end
end
end
VIEW
---------
<div id="chart1" style="height:300px; width:800px;"></div>
<script type="text/javascript">
$(document).ready(function(){
var line1=[<%= @graph_data %>];
var plot1 = $.jqplot('chart1', [line1], {
title:'Provisioned Accounts',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{
formatString:'%b %#d'
}
},
yaxis:{
tickOptions:{
formatString:'%.0f'
}
}
}
});
});
</script>
There are a few things I’d do differently here.
Move your find_by_sql into a method on
DailyProvisionedAccountsRollupcalled something like this:Then, in your controller you can just do this:
Finally, in your view you just use
@graph_data.to_jsonThat’s all untested code, but it should get you started cleaning up your controllers.