charts - Using instance methods with chartkick in a rails app -
i have model, teams has instance method point_differential (basically points - points against). trying use in chartkick graph, no luck.
this works
= bar_chart team.group(:group).sum(points_for)
because points_for attribute of team model.
this doesn't because point_differential instance method, not attribute
= bar_chart team.group(:name).sum(point_differential)
neither does
= bar_chart team.group(:name).sum(&:point_differential)
neither
bar_chart = team.all.map {|team| {name:team.name, point_differential: team.point_differential}}
any ideas?
your last option there correct, have wrong format.
consider first example:
team.group(:group).sum(:points_for)
this create hash following:
{"team a" => 14, "team b" => 9}
in last example did this:
team.all.map {|team| {name:team.name, point_differential: team.point_differential}}
which create an array of hashes following:
[{:name => "team a", :point_differential => 14}, {:name => "team b", :point_differential => 9}]
instead, try this:
hash[ *team.all.map { |team| [team.name, team.point_differential] }.flatten ]
this esoteric 1 liner takes array of arrays (each 2 elements), , creates hash out of them, giving this:
{"team a" => 14, "team b" => 9 }
like want.
another way, showing more steps this, this:
hash = {} team.all.each |team| hash[team.name] = team.point_differential end
then hash
have right values.
Comments
Post a Comment