0

我正在尝试为模型添加范围。我正在寻找从分贝计算总播放量。我在 Rails 3.2.13 上

MYSQL 查询提供了预期的结果。

SELECT COUNT(DISTINCT(CONCAT(stats.filename,stats.viewer_id)))
FROM `stats` 
WHERE `stats`.`user_id` = 4 
AND (stats.cf_status in ('Hit', 'Miss', 'RefreshHit', 'Error')) 
AND (date_time between '2013-04-14 05:00:00' and '2013-04-21 16:35:16')

= 169 次播放

我试图让这个范围工作,但是当我检查日志时 Rails 忽略了它。

统计模型

scope :only_valid, -> {
where("stats.cf_status in ('Hit', 'Miss', 'RefreshHit', 'Error')")
}
scope :totviews, -> {
where(" COUNT(DISTINCT(CONCAT(stats.filename,stats.viewer_id)))")
}

仪表板控制器 total_views:Stat.for_user(current_user).only_valid.between(@start_at,@end_at).totviews.count,

日志的输出 仍然显示原始查询而不是修改后的查询。

SELECT COUNT(*) 
FROM `stats` 
WHERE `stats`.`user_id` = 4 
AND (stats.cf_status in ('Hit', 'Miss', 'RefreshHit', 'Error')) 
AND (date_time between '2013-04-14 05:00:00' and '2013-04-21 17:17:29')

= 4589 次播放

任何帮助表示赞赏。谢谢

expose(:overview_chart_views) {
{
total_views:    to_col(Stat.for_user(current_user).only_valid.between(@start_at, @end_at).by_day),
total_viewers:  to_col(Stat.unique_plays.for_user(current_user).only_valid.between(@start_at, @end_at).by_day),
new_viewers:    to_col(Viewer.for_user(current_user).with_first_views.only_valid.between(@start_at, @end_at).by_day),
return_viewers: to_col(Viewer.for_user(current_user).without_first_views.only_valid.between(@start_at, @end_at).by_day)
}

private

def to_col(results)
lookup = {}
results.each {|row|
if !row['date'].kind_of?(Date)
row['date'] = Date.parse(row['date']);
end
lookup[row['date']] = row['result'].to_i }
(@start_at.to_date..@end_at.to_date).to_a.map {|date| lookup[date] || 0}
end
end
4

1 回答 1

0

totviews范围无效,因为您正在使用函数过滤元素count

尝试删除它并将查询更改为:

class Stat < ActiveRecord::Base
  def self.total_views
    Stat.for_user(current_user).only_valid.between(@start_at,@end_at).count('DISTINCT(CONCAT(stats.filename,stats.viewer_id))')
  end
end
于 2013-04-22T18:26:20.937 回答