2

在使用 chartkick gem 的应用程序中:

我有以下数据库表关系:

class User < ActiveRecord::Base
  has_many :games
  contains id, email
end

class Game < ActiveRecord::Base
  has_many :levels
  belongs_to :user
  #contains id, user_id, name

  accepts_nested_attributes_for :levels
end

class Level < ActiveRecord::Base
  belongs_to :game
  #contains id, score and game_id
end

我如何绘制每个玩家获得的分数?然后是每个玩家每场比赛获得的平均分数?

我想做类似的事情:

<%= column_chart Level.group(:user.email).sum(:score) %>

我设法做到了:

<%= column_chart Level.group(:game_id).sum(:score) %>

完整的代码可以在这里找到

4

2 回答 2

2

“我如何绘制每个玩家获得的分数?”

首先将此添加到用户:

has_many :levels, :through => :games

然后得到每个玩家的总分:

 User.includes(:levels).group(:email).sum(:score)

“然后是每个玩家每场比赛的平均得分?”

User.includes(:levels).group(:email, :game_id).average(:score)

This returns a hash with a tuple (email, game_id) as key and the average as value. Grouping by email is only to be able to get some user identification back in the results but there should be a nicer way to do it somehow.

于 2013-08-28T20:51:26.997 回答
0

您可以使用包含加入表格,

arel = Level.includes(:user, :game)

然后根据需要使用适当的查询,

arel = arel.group('user.email')

于 2013-08-14T13:14:45.467 回答