我有以下型号:
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 API says it’s deprecated.
我发现以下解决方案很简单:
Activity.sum(:occurrences).group(:activity_type_id)
其返回一个散列与activity_type_id =>发生.
我可以做什么来获取以下哈希:activity_type.name =>发生?
解决方法
如果原始查询工作,那么只需尝试使用Rails 3语法重写它:
Activity.joins(:activity_types) .select("activity_types.id,SUM(activities.occurrences) as occurrences") .group("activity_types.id,activity_types.name") .order("activity_types.id")