我正在尝试为模型添加范围。我想从db计算总播放次数。 我在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
答案 0 :(得分: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