我要做的就是按照过去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")
(“counts_impressions”用于避免帖子记录发生冲突)
然而,这会产生以下无效的SQL(counting_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
似乎只是忽略了select语句。我在哪里出错,或者我该怎么做才能使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
答案 0 :(得分:0)
试试这个:
scope :popular_last_week, unscoped .select(arel_table[Arel.star]) .select(Website.arel_table[:id].count.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")
答案 1 :(得分:0)
似乎查询应该是:
SELECT count(*) AS impression_count, w.id AS website_id
FROM websites as w
INNER JOIN impressions as i ON w.id = i.impressionable_id
WHERE w.is_published = 't' AND i.created_at >= '2013-01-11 17:48:03.954542'
GROUP BY w.id
ORDER BY impression_count DESC;
好像你可以跳过这个查询中的连接,然后对下一个查询运行“is_published”检查以获取实际的帖子数据...假设你只是使用这个查询来获取一个ID的列表第二个获取数据的查询。