Rails ActiveRecord 查询:每个类别的总文章查看次数

Rails ActiveRecord Query: Sum total article view count per category

我有可以分类标记的文章。我正在努力创建一个查询,该查询将提取每个类别中文章的浏览次数总和(使用印象派 gem 跟踪)。

架构:

  create_table "article_categories", force: :cascade do |t|
    t.integer "article_id"
    t.integer "category_id"
  end

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.bigint "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "impressions_count", default: 0
  end

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

文章模型

class Article < ApplicationRecord
  is_impressionable :counter_cache => true, :unique => false
  belongs_to :user
  has_many :impressions, as: :impressionable
  has_many :article_categories
  has_many :categories, through: :article_categories
end

类别模型

class Category < ApplicationRecord
  has_many :article_categories
  has_many :articles, through: :article_categories
end

文章分类模型

class ArticleCategory < ActiveRecord::Base
  belongs_to :article
  belongs_to :category
end

这是我到目前为止尝试过的方法以及我在 rails 控制台中测试时出现的错误:

cat_group = Article.joins(:article_categories).group_by(&:category_ids)
// this query results in an array of articles within each category

1) cat_group.sum("impressions_count")
//TypeError: no implicit conversion of Array into String

2) cat_group.select("sum(impressions_count) AS total_count")
//ArgumentError: wrong number of arguments (given 1, expected 0)

3) Article.joins(:article_categories).group(:category_id)

//ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "articles.id" must appear in the GROUP BY clause or be used in an aggregate function

如果我理解正确并且观看次数impressions_count,您可以使用以下查询:

Article.joins(:categories).group('categories.name').sum(:impressions_count)