Sign in through GitHub

Please read for an updated status on RailsCasts:

Learn more or hide this

Grant Spilsbury's Profile

GitHub User: grantspilsbury

Comments by Grant Spilsbury

Avatar

How would you create the graph grouped by 2 variables month and employee (for instance)?

ruby
Vote belongs_to :employee
Employee has_many :votes

Vote.chart_data

def self.chart_data(1.year.ago)
 total_count = count_by_month(start)
 start = start.to_date.beginning_of_month
 today = Date.today.beginning_of_month
 range = (start..today).select {|d| d.day == 1}
  range.map do |month|
  {
   created_at: month,
   total_enquiries: total_count[month] || 0
  }
 end
end

def self.count_by_month(start)
 enquiries = unscoped.where(created_at: start.beginning_of_day..Time.zone.now)
 enquiries = enquiries.group("date_trunc('month', created_at)")
 enquiries = enquiries.select("date_trunc('month', created_at) as created_at, count(*) as count")
 enquiries.each_with_object({}) do |enquiry, counts|
  counts[enquiry.created_at.to_date] = enquiry.count
 end
end

The morris graph expects this type of data for multiple lines

Morris.Line({
element: 'line-example',
data: [
{ y: '2006', a: 100, b: 90 },
{ y: '2007', a: 75, b: 65 },
{ y: '2008', a: 50, b: 40 },
{ y: '2009', a: 75, b: 65 },
{ y: '2010', a: 50, b: 40 },
{ y: '2011', a: 75, b: 65 },
{ y: '2012', a: 100, b: 90 }
],
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['Series A', 'Series B']
});