我要做的只是按过去 7 天的印象数(当有人查看帖子时创建印象)对帖子进行排序。这是我的命名范围
scope :popular_last_week, unscoped
.select("websites.*, COUNT(impressions.id) AS counted_impressions")
.joins("INNER JOIN impressions ON websites.id = impressions.impressionable_id")
.where("impressions.created_at >= ?", 7.days.ago)
.where(:is_published => true)
.group("websites.id")
.order("counted_impressions DESC")
(“counted_impressions”用于避免发布记录冲突)
然而,这会产生以下无效 SQL(counted_impressions 不是有效列):
SELECT COUNT(*) AS count_all, websites.id AS websites_id FROM "websites" INNER JOIN impressions ON websites.id = impressions.impressionable_id WHERE "websites"."is_published" = 't' AND (impressions.created_at >= '2013-01-11 17:48:03.954542') GROUP BY websites.id ORDER BY counted_impressions
似乎选择语句被忽略了。我哪里出错了,或者我应该怎么做才能使 SQL 语句为:
SELECT websites.*, COUNT(impressions.id) AS counted_impressions FROM "websites" INNER JOIN impressions ON websites.id = impressions.impressionable_id
WHERE "websites"."is_published" = 't' AND (impressions.created_at >= '2013-01-11 17:42:57.771777') GROUP BY websites.id ORDER BY counted_impressions DESC