[Chartjs]-Rails chart.js data coffee script

1πŸ‘

βœ…

Ok, the problem was that there was no data passed into the coffeescript.

I managed getting this done using the gem β€˜gon’. Here is what i did:

My app.js.coffee file looks like this:

jQuery ->
months = $.map( gon.sales, ( val, i ) -> 
            val.month
          );
amts = $.map( gon.sales, ( val, i ) -> 
            val.amount
          );

data = {
  labels : months,
  datasets : [
    {
      fillColor : "rgba(151,187,205,0.5)",
      strokeColor : "rgba(151,187,205,1)",
      pointColor : "rgba(151,187,205,1)",
      pointStrokeColor : "#fff",
      data : amts
    }
  ]
}

In my sales_controller.rb i’ve added the following:

def index
  @sales = Sale.all
  gon.sales = @sales
end

In my application.html.haml layout file:

= include_gon

And ofcourse in the Gemfile:

gem 'gon'

Finally in index.html.haml:

%canvas#canvas{:height => "400", :width => "600"}

And now the chart in dynamically populated with data from my sales table.

0πŸ‘

You need to fetch sum of amount by grouping on created_atβ€˜s month.

orders = Order.select("DATE_TRUNC('month', created_at) as month, SUM(amount) as sum_of_amount").group("month")
months = orders.collect(&:month)
amts = orders.collect(&:sum_of_amount)

Now you just need to pass months in labels: and amts in data:.

Good Luck!

Leave a comment