rails 3 group by和sum

时间:2012-01-30 18:35:54

标签: ruby-on-rails ruby-on-rails-3

我有以下型号:

activity_types: id, name

activities: id, id_activity_type, occurrences, date (other fields)

活动表存储活动按天发生的次数。但是现在我想向用户展示每个类型的活动按月发生了多少。

我得到了以下解决方案based on this post,似乎没问题:

Activity.all(:joins => :activity_types,
             :select => "activity_types.id, activity_types.name, SUM(activities.occurrences) as occurrences",
             :group => "activity_types.id, activity_types.name",
             :order => "activity_types.id")

但这似乎是rails标准和rails API says it's deprecated的许多代码。

我发现以下解决方案非常简单:

Activity.sum(:occurrences).group(:activity_type_id)

返回带有 activity_type_id =>的哈希值发生。

如何获取以下哈希值: activity_type.name =>发生?

2 个答案:

答案 0 :(得分:15)

如果原始查询有效,那么只需尝试使用Rails 3语法重写它:

Activity.joins(:activity_types)
  .select("activity_types.id, activity_types.name, SUM(activities.occurrences) as occurrences")
  .group("activity_types.id, activity_types.name")
  .order("activity_types.id")

答案 1 :(得分:4)

Activity.joins(:activity_types).group('activity_types.name').sum(:occurrences)

SELECT SUM(activities.occurrences) AS sum_occurrences, activity_types.name AS activity_types_name FROM activity_types INNER JOIN activity_types ON activity_types.id = activities.activity_types_id GROUP BY activity_types.name

如果您需要基于activity_types.id的有序哈希,并且假设不需要activity_types_id作为哈希键的一部分。

Activity.joins(:activity_types).group('activity_types.name').order(:activity_types_id).sum(:occurrences)

将[activity_type_id,activity_types.name]作为密钥

的一部分
Activity.joins(:activity_types).group(:activity_types_id, 'activity_types.name').order(:activity_types_id).sum(:occurrences)