How to quickly add graphs and charts to Rails app
When how to visualize data in your Rails app there are certain factors that you need to consider.
- You are probably working for a startup with monetary constraints so using libraries which cost $200 is something might want to avoid.
- You would prefer something looking good out of the box, which can also be easily styled by designers to follow the look&feel of the whole app.
- You would like something maintained so it continues working in the future with newer browser versions without spending much time in upgrades.
I am gonna propose you use Google Charts. Interactive and maintained by Google.
Model + SQL
class Order < ApplicationRecord def self.totals_by_year_month find_by_sql(<<-SQL SELECT date_trunc('month', created_at) AS year_month, sum(amount) as amount FROM orders GROUP BY year_month ORDER BY year_month, amount SQL ).map do |row| [ row['year_month'].strftime("%B %Y"), row.amount.to_f, ] end end end
date_truncis a PostgreSQL function which truncates the date to certain precision.
This methods returns the data in format such as:
[ ["July 2017", 346.0], ["July 2016", 50.0], ]
Obviously it is up to you what data and how you want to visualize :) This is just a simple example.
Get your data in controller
class OrdersController < ApplicationController def index @data = Order.totals_by_year_month end end
And that’s it. If your needs are simple, if you don’t need chart which dynamically changes values, if you just want draw a diagram, that’s enough.
- Expose the data via JSON API and obtain it using AJAX
- Dynamically translate the column names and chart title