Morgan
Morgan

Reputation: 140

Morris.js how to create graph for specific type

I have some troubles with create graph using Morris.js library. I created sport app and every training has some values. One of them is "workout" it means type of workout("Running","Swimming","Cycling"). I want to display line graph with date and distance, but for specific type of training, for example "Running". I created general graph with all dates and distances, but when I try to make graph for specific type it doesn't display proper one, but graph with sum of all running distances for every day(horizontal line). I don't know how to fix line in workouts_helper.rb distance: Workout.where(workout: "Running").sum(:distance)

workouts_helper.rb :

def running_chart_data
    (3.weeks.ago.to_date..Date.today).map do |date|
        {
            date: date,
            distance: Workout.where(workout: "Running").sum(:distance)
        }
    end
end

application.html.erb :

<script>
        new Morris.Line({
          element: 'running_chart',
          resize: true,
          data: $('#running_chart').data('running'),
          xkey: 'date',
          ykeys: ['distance'],
          labels: ['Distance']
        });
</script>

index.html.erb :

<h1>Last 3 weeks running graph</h1>

        <%= content_tag :div, "", id: "running_chart", data: {running: running_chart_data} %>

Upvotes: 0

Views: 197

Answers (1)

dinjas
dinjas

Reputation: 2125

Is distance a column in your Workout table, or is it a method in your Workout model?

If it's a column:

Workout
  .where(workout: 'Running')
  .sum(:distance)

should work fine.

If it's a method, you'll need to do something like:

Workout
  .where(workout: 'Running')
  .to_a
  .sum(&:distance)

Or

Workout
  .where(workout: 'Running')
  .sum{ |w| w.distance }

It's also worth noting that the query is going to return the same result set for every date in your range. If this is what you really want, it probably makes sense to move the query outside the iteration like this:

def running_chart_data
  distance = Workout
               .where(workout: 'Running')
               .sum{ |w| w.distance }

  ((Date.current - 3.weeks)..Date.current).map do |date|
    { date: date,
      distance: distance }
  end
end

Looking back over your question, I suspect that your issue might be that you're not taking date into account in your distance calculation.

You may want to add a check for the date like:

def running_chart_data
  ((Date.current - 3.weeks)..Date.current).map do |date|
    distance = Workout
                 .where(workout: 'Running',
                        created_at: date.beginning_of_day..date.end_of_day)
                 .sum(:distance) }

    {  date: date,
       distance: distance }
  end
end

Upvotes: 1

Related Questions