Rails group_by没有多个数据库调用

时间:2013-07-25 19:37:08

标签: ruby-on-rails postgresql activerecord scope enumerable

我的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

计算范围:

  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) }

group_by运行时,多个select语句运行以显然将对象组合在一起,无论如何还是要避免在对对象进行分组时这样做吗?

1 个答案:

答案 0 :(得分:1)

它只运行多个查询来获取我怀疑您可以加入原始查询的信息。

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

这将加载关联的stat_typestat_type_category个对象。

这是基于几个假设。

首先,它们都是单基数关联。即has_one :stat_typebelongs_to :stat_type - 否则您将从查询中获得太多结果。

其次,将要返回的所有Stat个实例都有stat_typestat_type_category。如果他们不这样做,那么joins的查询将不会返回它们。

您可能也只想在需要分组时进行连接,否则您将运行比您需要的更完整的查询。 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