简体   繁体   English

在Rails应用程序中将实例方法与Chartkick一起使用

[英]Using instance methods with chartkick in a rails app

I have a model, teams that has an instance method point_differential (basically points for - points against). 我有一个模型,有一个实例方法point_differential(基本上是-反对)的团队。 I am trying to use it in a chartkick graph, but with no luck. 我试图在图表图表中使用它,但是没有运气。

This works 这有效

= bar_chart Team.group(:group).sum(points_for) = bar_chart Team.group(:group).sum(points_for)

because points_for is just an attribute of the Team model. 因为points_for只是Team模型的一个属性。

This doesn't because point_differential is an instance method, not an attribute 这不是因为point_differential是实例方法,而不是属性

= bar_chart Team.group(:name).sum(point_differential) = bar_chart Team.group(:name).sum(point_differential)

Neither does 也没有

= bar_chart Team.group(:name).sum(&:point_differential) = bar_chart Team.group(:name).sum(&:point_differential)

Neither does 也没有

bar_chart = Team.all.map {|team| bar_chart = Team.all.map {| team | {name:team.name, point_differential: team.point_differential}} {name:team.name,point_differential:team.point_differential}}

Any ideas? 有任何想法吗?

Your last option there is almost correct, but you have the wrong format. 您的最后一个选项几乎是正确的,但是格式错误。

Consider your first example: 考虑您的第一个示例:

Team.group(:group).sum(:points_for)

This would create a hash like the following: 这将创建如下所示的哈希:

{"Team A" => 14, "Team B" => 9}

In your last example you did this: 在上一个示例中,您执行了以下操作:

Team.all.map {|team| {name:team.name, point_differential: team.point_differential}}

Which would create an array of hashes like the 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 is an esoteric one liner that takes an array of arrays (each 2 elements), and creates a hash out of them, giving you something like this: 这是一个深奥的衬板,它需要一个数组数组(每个2个元素),并从它们中创建一个哈希,从而为您提供以下内容:

{"Team A" => 14, "Team B" => 9 }

Like you want. 像你要的那样。

Another way, showing more steps to do this, is like this: 另一种显示更多步骤的方法是这样的:

hash = {}
Team.all.each do |team|
  hash[team.name] = team.point_differential
end

Then that hash will have the right values. 然后,该hash将具有正确的值。

I resolved this by writing a class method to build a hash using inject 我通过编写一个类方法来解决这个问题,该方法使用注入来构建哈希

def self.hashify_points_differential
   Player.all.inject({}) do |result, player|
     result[player.name] = player.point_differential
     result
    end   
end

Then I can just use it like 然后我可以像这样使用它

= bar_chart Player.hashify_points_differential

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM