0

I have the following method in my concern:

  def all_calculated_stats(sport, group = false)
    calculated_stats = Stat.calculated(sport.id, id)
    calculated_stats = calculated_stats.group_by { |stat| stat.stat_type.stat_type_category.name } if group
    return calculated_stats
  end

calculated scope:

  scope :calculated, ->(sport_id, athlete_id) { joins(:stat_type => :stat_type_category).where('stat_types.calculated = ? AND stat_type_categories.sport_id = ? AND stats.athlete_id = ?', true, sport_id, athlete_id) }

When the group_by is ran multiple select statements run to obviously group the objects together, is there anyway to avoid doing this while still grouping the objects?

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

1 Answers1

1

It is only running multiple queries to get information that I suspect you could join in your original query.

Stat.calculated(sport.id, id).joins(:stat_type => :stat_type_category)

That will load the associated stat_type and stat_type_category objects.

This is based on a couple of assumptions though.

Firstly that they are both single cardinality associations. I.e. has_one :stat_type or belongs_to :stat_type - otherwise you'll get too many results coming back from the query.

Secondly that all Stat instances that are going to be returned have a stat_type with a stat_type_category. If they don't then they won't be returned by a query with joins.

You might also only want to do the join when you need to group otherwise you'll be running a more complete query than you need. E.g.

calculated_stats = Stat.calculated(sport.id, id)
if group
  calculated_stats = calculated_stats.joins(:stat_type => :stat_type_category)
  calculated_stats = calculated_stats.group_by { |stat| stat.stat_type.stat_type_category.name }
end
return calculated_stats
Shadwell
  • 34,314
  • 14
  • 94
  • 99