Question

In an app using the chartkick gem:

I have the following database table relations:

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

How do i plot the score acquired by each player? And then the average score acquired by each player each game?

I want to do something like:

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

I managed to do:

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

The entire code can be found here

Was it helpful?

Solution

"How do i plot the score acquired by each player?"

First add this to User:

has_many :levels, :through => :games

Then get the total score per player with:

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

"And then the average score acquired by each player each game?"

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.

OTHER TIPS

You can join the tables using includes,

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

Then use appropriate query as you want to,

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top